Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
102 views
in Technique[技术] by (71.8m points)

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

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:UsersAndreasdocumentsvisual studio 2010ProjectsLoginApplicationLoginApplicationloginDB.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.

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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 BINDEBUG 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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...