I am executing SQL command INSERT
like this in my Visual C#.NET using MS VS 2010 Express Edition:
private void btnAdd_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(Properties.Settings.Default.loginDBConnectionString);
con.Open();
SqlCommand cmd = new SqlCommand("INSERT INTO tblEmp (ID, firstname, lastname, email, position) VALUES ('"+textBox1.Text+"','"+textBox2.Text+"', '"+textBox3.Text+"', '"+textBox4.Text+"', '"+comboBox1.Text+"')", con);
cmd.ExecuteNonQuery();
con.Close();
MessageBox.Show("Data Added!");
}
When executing this, the MessageBox
showed up which means the execution was successful. But, when I checked on the table , the data that I am trying to insert before isn't appear at all.
I have one database (loginDB.mdf
) with 2 tables inside :
- TblLogin
- contains username
and password
for login purpose which executed successfully.
- tblEmp
- contains employee data, this is the one that I tried to insert data to.
What I don't understand is why the MessageBox
appear when in fact none inserted into my tblEmp
.
EDIT : ConnectionString
to loginDB.mdf
:
Data Source=.\SQLEXPRESS;AttachDbFilename="C:\Users\Andreas\documents\visual studio 2010\Projects\LoginApplication\LoginApplication\loginDB.mdf";Integrated Security=True;User Instance=True
The database name is loginDB.mdf
instead of logindatabase.mdf
as previously written. I changed it to loginDB.mdf
just to test it, but still no changes appear.
ID
an identity column which auto generates it's value on insert? Always use parameterized queries instead of string concatenation to build your sql queries. Otherwise ypou are vulnerable to sql injection. – CrenelateExecuteNonQuery
method? Is it returns1
exactly? What is your variables? Have you ever tried your query in your database manager first? – Mindszentyusing
construction forSqlConnection
(and for otherIDisposable
s). – Huh