SQL command INSERT is working but the data not appear in table

孤人 提交于 2019-12-17 01:13:26

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/31604951/sql-command-insert-is-working-but-the-data-not-appear-in-table

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!