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();
}
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 insert data into a database that I have that has a table called EmployeeInfo
The user is prompted to enter a last name and select a department ID (displayed to the user as either marketing or development) The column ID automatically increments.
Here is my Code behind
protected void SubmitEmployee_Click(object sender, EventArgs e)
{
var submittedEmployeeName = TextBox1.Text;
var submittedDepartment = selectEmployeeDepartment.Text;
if (submittedEmployeeName == "")
{
nameError.Text = "*Last name cannot be blank";
}
else
{
System.Data.SqlClient.SqlConnection sqlConnection1 =
new System.Data.SqlClient.SqlConnection("ConnString");
System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand();
cmd.CommandType = System.Data.CommandType.Text;
cmd.CommandText = "INSERT INTO EmployeeInfo (LastName, DepartmentID ) VALUES ('" + submittedEmployeeName + "', " + submittedDepartment + ")";
cmd.Connection = sqlConnection1;
sqlConnection1.Open();
cmd.ExecuteNonQuery();
sqlConnection1.Close();
}
}
The error I'm recieving is 'Arguement exception was unhandled by user code'
Here is a picture of it.
As requested. More details
If I had enough reputation, I would rather post this as a reply, but it might actually be the solution.
The reason why it stops there is because you are not providing a legit SqlConnection, since your input is: "ConnString", which is just that text.
The connection string should look something like:
const string MyConnectionString = "SERVER=localhost;DATABASE=DbName;UID=userID;PWD=userPW;"
Which in your case should end up like:
System.Data.SqlClient.SqlConnection sqlConnection1 = new System.Data.SqlClient.SqlConnection(MyConnectionString);
Besides that, you should build your connections like following:
using (SqlConnection con = new SqlConnection(MyConnectionString)) {
using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandText = xxxxxx; // Your query to the database
cmd.Connection = con;
cmd.Connection.Open();
cmd.ExecuteNonQuery();
}
}
This will do the closing for you and it also makes it easier for you to nestle connections. I did a project recently and did the connection your way, which ended up not working when I wanted to do more than one execute in one function. Just important to make a new command for each execute.
I am building a database using Visual Studio 2008 c# and when I'm a trying to insert a new record into my database it appears that ExecuteNonQuery has not initialized. I copy my code, hope anyone can help me in this because I am new.
private void button1_Click(object sender, EventArgs e)
{
SqlConnection cn = new SqlConnection(#"Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Users\Usuario\Documents\Visual Studio 2010\Projects\Nova\Nova\Database1.mdf;Integrated Security=True;User Instance=True");
SqlCommand cmd = new SqlCommand();
cn.Open();
cmd.CommandText = "insert into Database1.mdf(Codigo,Nombre,Cantidad,Tipo) values('"+comboBox1.Text+"','"+textBox3.Text+"','"+textBox1.Text+"','"+comboBox2.Text+"')";
cmd.ExecuteNonQuery();
cmd.Clone();
cn.Close();
MessageBox.Show("Acabas de agregar un producto");
}
You haven't set the connection to your command:
cmd.Connection = cn;
You have numerous problems in your code:
First: The insert into statement requires a target datatable not the name of
the MDF file
Second: Employ the using statement to close and dispose the connections
Third: Parametrized query to avoid parsing problems and sql
injections
Fourth: You need to associate the connection to the command (Easily
done at the SqlCommand constructor)
using(SqlConnection cn = new SqlConnection(.......))
using(SqlCommand cmd = new SqlCommand("insert into table_name(Codigo,Nombre,Cantidad,Tipo)" +
"values (#cod, #nom,#can,#tipo)", con))
{
cn.Open();
cmd.Parameters.AddWithValue("#cod", comboBox1.Text);
cmd.Parameters.AddWithValue("#nom", textBox3.Text);
cmd.Parameters.AddWithValue("#can", textBox1.Text);
cmd.Parameters.AddWithValue("#tipo", comboBox2.Text);
cmd.ExecuteNonQuery();
MessageBox.Show("Acabas de agregar un producto");
}
EDIT
The information provided by the link added by #RemusRusanu below is very important. The use of AddWithValue, whilst handy, could hinder the performance of your query. The correct approach should be the usage of a proper defined SqlParameter with both explicit datatype and parameter size.
As an example
SqlParameter p = new SqlParameter("#cod", SqlDbType.NVarChar, 255).Value = comboBox1.Text;
cmd.Parameters.Add(p);
But, of course, this requires that you check the exact datatype and size of your columns.
You did not initialize your SqlCommand with a connection. Also, you should really enclose everything here with using. And consider using parametarized commands to avoid SQL Injection.
private void button1_Click(object sender, EventArgs e)
{
using (SqlConnection cn = new SqlConnection(#"Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Users\Usuario\Documents\Visual Studio 2010\Projects\Nova\Nova\Database1.mdf;Integrated Security=True;User Instance=True"))
{
using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandText = "insert into databaseTableName (Codigo,Nombre,Cantidad,Tipo) values (#Codigo, #Nombre, #Cantidad, #Tipo)";
cmd.Parameters.AddWithValue("#Codigo", comboBox1.Text);
cmd.Parameters.AddWithValue("#Nombre", textBox3.Text);
cmd.Parameters.AddWithValue("#Cantidad", textBox1.Text);
cmd.Parameters.AddWithValue("#Tipo", comboBox2.Text);
cmd.Connection = cn; //this was where the error originated in the first place.
cn.Open();
cmd.ExecuteNonQuery();
MessageBox.Show("Acabas de agregar un producto");
}
}
}
I'm Having some trouble deleting an entry on my database.
I can insert data, but i can't delete them.
I have a 2 variables database, and i want to manage those data.
but when i debug the program , the first button (btnAdicionar) works fine, but when i press the button "btnRemover", i get an erron on the line "cmd.ExecuteNonQuery();"
what am i doing wrong? thanks
here is the code:
private void btnAdicionar_Click(object sender, EventArgs e)
{
OleDbConnection conn = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=c:\\BancodeDados\\Nomes.mdb");
string sql = "INSERT INTO Nomes (Nome, Sobrenome) VALUES(?, ?)";
OleDbCommand cmd = new OleDbCommand(sql, conn);
conn.Open();
cmd.Parameters.AddWithValue("Nome", txtNome.Text);
cmd.Parameters.AddWithValue("Sobrenome", txtSobre.Text);
cmd.ExecuteNonQuery();
conn.Close();
this.nomesTableAdapter.Fill(this.nomesDataSet.Nomes);
}
private void btnRemover_Click(object sender, EventArgs e)
{
OleDbConnection conn = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=c:\\BancodeDados\\Nomes.mdb");
string sql = "DELETE FROM Nomes (Nome, Sobrenome) WHERE (?, ?)";
OleDbCommand cmd = new OleDbCommand(sql, conn);
conn.Open();
cmd.Parameters.AddWithValue("Nome", txtNome.Text);
cmd.Parameters.AddWithValue("Sobrenome", txtSobre.Text);
cmd.ExecuteNonQuery();
conn.Close();
this.nomesTableAdapter.Fill(this.nomesDataSet.Nomes);
}
Your delete statement is not valid SQL, hence the error when you call ExecuteNonQuery
It should be something like this:
DELETE FROM Nomes WHERE Nome= ? and Sobrenome = ?
I have a table student (id, name). Then I have one textbox, for entering the name, when click on submit button, it inserts the data into the database. So how can I insert only to name, not id because id is auto increment?
I tried this
insert into student(id, name) values(,name)
but it is not insert to my table.
This is my code :
protected void Button1_Click(object sender, EventArgs e)
{
string test = txtName.Text;
SqlConnection conn = new SqlConnection(#"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Person.mdf;Integrated Security=True;User Instance=True");
string sql = "insert into student(name) values ('test')";
try
{
conn.Open();
SqlCommand cmd = new SqlCommand(sql, conn);
cmd.ExecuteNonQuery();
}
catch (System.Data.SqlClient.SqlException ex)
{
string msg = "Insert Error:";
msg += ex.Message;
}
finally
{
conn.Close();
}
}
INSERT INTO student (name) values ('name')
Omit the id column altogether, it will be populated automatically. To use your variable, you should parameterise your SQL query.
string sql = "INSERT INTO student (name) values (#name)";
conn.Open();
SqlCommand cmd = new SqlCommand(sql, conn);
cmd.Parameters.Add("#name", SqlDbType.VarChar);
cmd.Parameters["#name"].Value = test;
cmd.ExecuteNonQuery();
You should never attempt to do this by constructing a SQL string containing the input value, as this can expose your code to SQL injection vulnerabilities.
You better use parameters when you insert data.
try
{
string sql = "insert into student(name) values (#name)";
using (SqlConnection conn = new SqlConnection(connectionString))
{
conn.Open();
using (SqlCommand cmd = new SqlCommand(sql, conn))
{
cmd.Parameters.AddWithValue("#name", test); // assign value to parameter
cmd.ExecuteNonQuery();
}
}
}
catch (SqlException ex)
{
string msg = "Insert Error:";
msg += ex.Message;
}
You don't need to mention the ID in first part.
insert into student(name) values('name')
I was facing this problem and after trying various solution found at stack overflow, i could summarize the experience as follows:
commands executed in command shell of mssql like:
insert into table_name (val1,val2,val3,val4) VALUES ("val1","val2",0,"val4")
go
or
insert into table_name VALUES ("val1","val2",0,"val4")
go
work when typed directly in the mssql database prompt,
But when it is required to use the the insert statement from c#, it is required to be kept in mind that string needs to be surrounded by an additional pair of single quites, around the strings, like in:
SqlConnection cnn;
string connetionString = "Data Source=server_name;Initial Catalog=database_name;User ID=User_ID;Password=Pass_word";
cnn = new SqlConnection(connetionString);
SqlCommand myCommand = new SqlCommand("insert into table_name (val1,val2,val3,val4) VALUES ('val1','val2',0,'val4');", cnn);
//or
//SqlCommand myCommand = new SqlCommand(insert into table_name VALUES ('val1','val2',0,'val4');", cnn);
cnn.Open();
myCommand.ExecuteNonQuery();
cnn.Close();
the problem here is that most people, like myself, try to use <\"> in the place of double quotes <">that is implemented as in the above command line case, and SQL executor fails to understand the meaning of this.
Even in cases where a string needs to be replace, ensure that strings are surrounded by single quotation, where a string concatination looks like a feasible solution, like in:
SqlCommand myCommand = new SqlCommand("insert into table_name (val1,val2,val3,val4) VALUES ('"+val1+"','val2',0,'val4');", cnn);
string sql = "INSERT INTO student (name) values (#name)";
conn.Open();
SqlCommand cmd = new SqlCommand(sql, conn);
cmd.Parameters.Add("#name", SqlDbType.VarChar);
cmd.Parameters["#name"].Value = test;
cmd.ExecuteNonQuery();
Try the following query,
insert into student(name) values(name)
SQL Server internally auto increments the id column when u insert the data since u said it is auto increment. If it is not working, the u have to check the identity column in the db.
use the key word "identity" to auto increment the id column
Refer : http://technet.microsoft.com/en-us/library/aa933196(v=sql.80).aspx
create table table_name( id int PRIMARY KEY IDENTITY )
and you no need to mention the "id" in the insert query