問題描述
我正在使用 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 正在工作,但數據未出現在表中的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!