问题描述
我正在使用 MS VS 2010 Express Edition 在我的 Visual C#.NET 中像这样执行 SQL 命令 INSERT
:
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!");
}
执行时出现MessageBox
,表示执行成功.但是,当我检查表格时,我之前尝试插入的数据根本没有出现.
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.
我有一个数据库(loginDB.mdf
),里面有 2 个表:- TblLogin
- 包含 username
和 password
用于成功执行的登录目的.- tblEmp
- 包含员工数据,这是我尝试插入数据的数据.
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.
我不明白的是为什么 MessageBox
实际上没有插入到我的 tblEmp
中.
What I don't understand is why the MessageBox
appear when in fact none inserted into my tblEmp
.
编辑:ConnectionString
到loginDB.mdf
:
Data Source=.SQLEXPRESS;AttachDbFilename="C:UsersAndreasdocumentsvisual studio 2010ProjectsLoginApplicationLoginApplicationloginDB.mdf";Integrated Security=True;User Instance=True
数据库名称是 loginDB.mdf
而不是之前写的 logindatabase.mdf
.我把它改成 loginDB.mdf
只是为了测试它,但仍然没有出现任何变化.
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.
推荐答案
如果您的 c# 代码执行时没有任何异常,它也会更新数据库.您可能在 ConnectionString
中使用过 AttachDbFilename=|DataDirectory|yourDB.mdf
,这意味着更新的数据库位于子文件夹 BINDEBUG
项目的文件夹.如果您想查看更新的数据,只需附加位于 ssms 中 bin/debug
文件夹中的数据库.有关详细信息,请阅读 此 帖子.还要确保服务器资源管理器中的表尚未打开,如果它已经打开,则必须刷新它以显示更新的数据.请注意:正如评论中提到的,您应该始终使用参数化查询来避免Sql 注入
.
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
.
这篇关于SQL 命令 INSERT 正在工作,但数据未出现在表中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!