SQL command INSERT is working but the data not appear in table
If your c# code executes without any exceptions, it updates the database too. You have probably used AttachDbFilename=|DataDirectory|\yourDB.mdf
in your ConnectionString
, that means the databse that is updated is located in the subfolder BIN\DEBUG
folder of your project. If you want to see the updated data just attach the database located in the bin/debug
folder in ssms.
for more details read this post.
Also make sure your table in server explorer is not already open, if it is already open you must refresh it to show updated data. Please note:as mentioned in the comments you should always use parameterized queries to avoid Sql Injection
.
Andreas Adhiguna Hartono
Updated on June 04, 2022Comments
-
Andreas Adhiguna Hartono almost 2 years
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
- containsusername
andpassword
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 mytblEmp
.EDIT :
ConnectionString
tologinDB.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 oflogindatabase.mdf
as previously written. I changed it tologinDB.mdf
just to test it, but still no changes appear.