问题
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