i have been trying to insert data to my database with ASP.net
the code with which i have been trying to insert data:
protected void btnInsert_Click(object sender, EventArgs e)
{
// connection
SqlConnection connection = new SqlConnection();
connection.ConnectionString = #"Data Source=YANNICK\SQLEXPRESS; Initial Catalog=Klas; Integrated Security=True";
SqlCommand command = new SqlCommand();
command.Connection = connection;
// values de insert statement toewijzen
command.Parameters.AddWithValue("#kijkerv", txtGastV.Text);
command.Parameters.AddWithValue("#kijkerT_V", txtGastT_V.Text);
command.Parameters.AddWithValue("#KijkerA", txtGastA.Text);
command.Parameters.AddWithValue("#KijkerEmail", txtEmail.Text);
command.Parameters.AddWithValue("#Kijkershow", txtShowId.integer;
// insert statement
command.CommandText = "INSERT INTO tblKijker (Kijkerv, KijkerT_V, KijkerA, ShowId, Email) VALUES (#kijkerv,
#kijkerT_V, #KijerA, #KijkerEmail, #Kijkershow);";
try {
connection.open();
int rowsAffected = command.ExecuteNonQuery();
} catch (Exception ex) {
// handle exception
} finally {
connection.close();
}
}
the error message is: newline in constant
what does this error mean/ how to fix it?
Your query string CommandText is in two lines. Remove the newline or put # before your query string like this :
command.CommandText = #"INSERT INTO tblKijker (Kijkerv, KijkerT_V, KijkerA, ShowId, Email) VALUES (#kijkerv,
#kijkerT_V, #KijerA, #KijkerEmail, #Kijkershow);"
i have found my own problem:
i had forgotten to add the libraries to set up a connction to my sql into my file
the code would look like this:
// library to work in DATABASES
using System.Data;
// library especially for SQL
using System.Data.SqlClient;
Related
This is the code I'm working with right now, I don't get any errors so I can't pinpoint where it's not working:
private void btnAdd_Click(object sender, EventArgs e)
{
string constring = $"Data Source=(LocalDB)\\MSSQLLocalDB;AttachDbFilename=" +
Directory.GetCurrentDirectory().ToString() + "\\BarcodeDB.mdf;Integrated Security=True";
string query =
"INSERT INTO Products (Barcodes, Name, EDate, Quantity, Price) VALUES (#barcodeValue, #nameValue, #dateValue, #quantityValue, #priceValue) ;";
SqlConnection conDataBase = new SqlConnection(constring);
conDataBase.Open();
using (var cmd = new SqlCommand(query, conDataBase))
{
cmd.Parameters.AddWithValue("#barcodeValue", tbxBar.Text);
cmd.Parameters.AddWithValue("#nameValue", tbxName.Text);
cmd.Parameters.AddWithValue("#dateValue", dateDate.Value.Date);
cmd.Parameters.AddWithValue("#quantityeValue", tbxQua.Text);
cmd.Parameters.AddWithValue("#priceValue", tbxPrice.Text);
}
conDataBase.Close();
}
The code might just be wrongly build or I could be missing some part I'm not sure.
I figured out what was not working, was the connection string. So opening a new question for that.
What i had to do is to open the connection and then execute the command
You're not actually running the command. You need to call ExecuteNonQuery or ExecuteScalar:
using (var cmd = new SqlCommand(query, conDataBase))
{
// set parameters...
cmd.ExecuteNonQuery();
}
I am trying to build a registration web form which saves user data into an SQL table. This is what I have so far:
public static SqlConnection GetConnection()
{
String connection;
connection = #"example/file/path";
return new SqlConnection(connection);
}
protected void submitButton_Click(object sender, EventArgs e)
{
SqlConnection myConnection = GetConnection();
try
{
myConnection.Open();
String myQuery = "INSERT INTO RegistrationDB([firstName], [lastName], [eMail], [dob], [userName], [password]) values ('"
+fNameBox.Text+ "' ,'"+ lNameBox.Text+"' ,'"+emailBox.Text+"' ,'"
+ dobBox.Text+"', '"+userNameBox.Text+"' ,'"+passwordBox.Text+"';)";
SqlCommand myCommand = new SqlCommand(myQuery, GetConnection());
myCommand.ExecuteNonQuery();
myConnection.Close();
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
finally
{
myConnection.Close();
}
}
The error occurs in my GetConnection() method where I return the connection. The error I get is:
An exception of type 'System.ArgumentException' occurred in
System.Data.dll but was not handled in user code
Additional information: Format of the initialization string does not conform to specification starting at index 0.
I do not know how to get past this problem but any help is very appreciated.
Your problem lies in
String connection;
connection = #"example/file/path";
return new SqlConnection(connection);
your connectionString variable (connection in your case) is not set properly, there are multiple ways to do that just to list 2 of the most common ones.
Standard Connection with username and password:
SqlConnection conn = new SqlConnection();
conn.ConnectionString =
"Data Source=ServerName;" +
"Initial Catalog=DataBaseName;" +
"User id=UserName;" +
"Password=Secret;";
conn.Open();
Trusted Connection:
SqlConnection conn = new SqlConnection();
conn.ConnectionString =
"Data Source=ServerName;" +
"Initial Catalog=DataBaseName;" +
"Integrated Security=SSPI;";
conn.Open();
You might want to look at this question for example:
How to set SQL Server connection string?
Pijemcolu's answer is correct, but I think several things can be added to enhance your code:
1) use proper names for variables. E.g.: connection string is different from actual connection
public static SqlConnection GetConnection()
{
// if Windows Authentication is used, just get rid of user id and password and use Trusted_Connection=True; OR Integrated Security=SSPI; OR Integrated Security=true;
String connStr = "Data Source=ServerName;Initial Catalog=DataBaseName;User id=UserName;Password=Secret;";
return new SqlConnection(connStr);
}
2) Try to dispose disposable objects (i.e. implement IDisposable) should be properly disposed.
Also, commands should not constructed with string concatenation, but using parameters. This is particularly important when providing direct user input into the query, since malicious users might try to perform queries to compromise the data (read more about SQL injection here).
The connection can be closed only within finally block, since everything there is executed no matter what (exception raised or not in the catch block).
protected void submitButton_Click(object sender, EventArgs e)
{
SqlConnection myConnection = null;
try
{
using (myConnection = GetConnection())
{
myConnection.Open();
String myQuery = #"
INSERT INTO RegistrationDB([firstName], [lastName], [eMail], [dob], [userName], [password])
values (#firstName, #lastName, #eMail, #dob, #userName, #password)";
using (SqlCommand myCommand = new SqlCommand(myQuery, GetConnection())
{
myCommand.Parameters.AddWithValue("#firstName", fNameBox.Text);
myCommand.Parameters.AddWithValue("#lastName", lNameBox.Text);
myCommand.Parameters.AddWithValue("#eMail", emailBox.Text);
myCommand.Parameters.AddWithValue("#dob", dobBox.Text);
myCommand.Parameters.AddWithValue("#userName", userNameBox.Text);
myCommand.Parameters.AddWithValue("#password", passwordBox.Text);
myCommand.ExecuteNonQuery();
}
}
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
finally
{
if (myConnection != null)
myConnection.Close();
}
}
3) Password storage
It looks like your storing password typed by the user. It is strongly recommended to store a representation of the password (some sort of hash that it is easy to compute from a string, but the string is almost impossible to be retrieved from the hash). More details can be found here.
I have a very basic and beginner problem. I got a 5 line code and I got exception in that.
My database :
It has one table and two columns inside the table viz. id and name.
I made a form.
Here is my code:
private void button1_Click(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection("Data Source=(LocalDB)\\v11.0;AttachDbFilename=\"C:\\Users\\Nicki\\documents\\visual studio 2012\\Projects\\WindowsFormsApplication2\\WindowsFormsApplication2\\Database2.mdf\";Integrated Security=True");
conn.Open();
SqlCommand command = new SqlCommand("INSERT INTO Table (id,name) VALUES (1,'" + textBox1.Text + "')", conn);
command.ExecuteNonQuery();
conn.Close();
}
I get the following exception on running the code:
It says that I have syntax error even though the syntax error is correct. Any help would be appreciated.
Thankyou!
You should use a using clause to properly manage resources and use parameters to avoid security problems. It is not recommended to use reserved words as "table". Try this:
const string commandText = "INSERT INTO [Table] (id,name) VALUES (1,#Name)";
using (SqlConnection connection = new SqlConnection(ConnectionString))
{
SqlCommand command = new SqlCommand(commandText, connection);
command.Parameters.Add("#Name", SqlDbType.VarChar);
command.Parameters["#Name"].Value = textBox1.Text;
connection.Open();
var rowsAffected = command.ExecuteNonQuery();
}
Could somebody tell me why this isn't adding the values to the database. The form runs fine and doesn't return any errors.
private void button1_Click(object sender, EventArgs e)
{
SqlConnection connection = new SqlConnection();
SqlCommand command = new SqlCommand();
connection.ConnectionString = (#"Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Users\John\Documents\Setup.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True");
command.Parameters.AddWithValue("#userName", textBox1.Text);
command.Parameters.AddWithValue("#passWord", textBox2.Text);
command.CommandText = "INSERT INTO Setup (userName, password) VALUES(#userName, #passWord)";
try
{
connection.Open();
int rowsAffected = command.ExecuteNonQuery();
}
catch (Exception ex)
{
// handle exception
}
finally
{
connection.Close();
}
}
FYI: I'm a "newbie" My database is called Setup. I've manually added a table called myTable with 2 columns of userName and another one called password both set at nchar(50)
You need to specify the Table, not the database (which gets used in the connection string). Added the schema prefix to the table name:
command.CommandText = "INSERT INTO dbo.myTable (userName, password) VALUES (#userName, #passWord)";
And add:
command.Connection = connection;
to associate your Command object with the connection object.
Your code should look something like this:
Set the connection object.
Specify the table name as #LarsTech has mentioned.
It is a best practice to use two part notation when specifying table names like [Schema name].[Table Name]. So, you have to specify your table name like dbo.MyTable
Code snippet:
private void button1_Click(object sender, EventArgs e)
{
SqlConnection connection = new SqlConnection();
connection.ConnectionString = (#"Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Users\John\Documents\Setup.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True;");
SqlCommand command = new SqlCommand();
command.Connection = connection;
command.CommandText = "INSERT INTO dbo.MyTable (userName, password) VALUES (#userName, #passWord)";
command.Parameters.AddWithValue("#userName", textBox1.Text);
command.Parameters.AddWithValue("#passWord", textBox2.Text);
try
{
connection.Open();
int rowsAffected = command.ExecuteNonQuery();
}
catch (Exception ex)
{
//handle exception
}
finally
{
connection.Close();
}
}
The form runs fine and doesn't return any errors.
That's probably because you're swallowing them. Get rid of (or log) your catch (Exception ex).
In general, the .NET BCL is well-designed - if a method isn't going to work, you will get an exception.
[Now] I have the error 'ExecuteNonQuery: Connection property has not been initialized.'
Right. You need to pass the SqlConnection to the SqlCommand:
SqlCommand command = new SqlCommand();
command.Connection = connection;
I have a simple two-field form that stores its data in the database. For some reason, it isn't working. I have verified that the connection string works, as it is used in another project I made.
I didn't include the beginning of the first class or its page load.
Code:
protected void btnSubmit_Click(object sender, EventArgs e)
{
string Name = txtName.Text;
string Description = txtSpecial.Text;
string method = string.Format(
"INSERT INTO RbSpecials (Name,Description,Active) VALUES ('{0}','{1}','1')",
Name,
Description);
RbConfiguration mySql = new RbConfiguration();
try
{
mySql.Sql_Connection(method);
}
catch
{
}
}
}
public class RbConfiguration
{
string DbConnectionString = "System.Configuration.ConfigurationManager.ConnectionStrings['RBConnectionString'].ConnectionString";
public void Sql_Connection(string queryString)
{
SqlConnection conn = new SqlConnection(DbConnectionString);
SqlCommand cmd = new SqlCommand(queryString, conn);
conn.Open();
conn.Close();
}
}
You never execute your SQL command:
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
And your connection string is wrong (ditch the double quotes):
string DbConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings["RBConnectionString"].ConnectionString;
Well without knowing the error, I'll give it a shot anyway.
string DbConnectionString = "System.Configuration.ConfigurationManager.ConnectionStrings['RBConnectionString'].ConnectionString";
Should be
string DbConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings["RBConnectionString"].ConnectionString;
And as Adam says, you never actually execute your Query.
The Sql_Connection-method, only opens a connection, and then closes it again, without actually doing anything.
Try this instead:
public void Sql_Connection(string queryString)
{
using( SqlConnection conn = new SqlConnection(DbConnectionString) )
{
SqlCommand cmd = new SqlCommand(queryString, conn);
conn.Open();
cmd.ExecuteNonQuery();
}
}
Check your connection string code must not be a string its class which is getting connection string from web.config, so it should be like this
string DbConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings["RBConnectionString"].ConnectionString;
You did not execute your SQlCommand, so will it insert the data, do this
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
its not the cause but the best practice to not to make your code vulnerable to SQLINjection, try this article
How To: Protect From SQL Injection in ASP.NET