有人可以告訴我爲什麼這不會將值添加到數據庫。表單運行正常,不會返回任何錯誤。C#數據庫問題
private void button1_Click(object sender, EventArgs e)
{
SqlConnection connection = new SqlConnection();
SqlCommand command = new SqlCommand();
connection.ConnectionString = (@"Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Users\John\Documents\Setup.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True");
command.Parameters.AddWithValue("@userName", textBox1.Text);
command.Parameters.AddWithValue("@passWord", textBox2.Text);
command.CommandText = "INSERT INTO Setup (userName, password) VALUES(@userName, @passWord)";
try
{
connection.Open();
int rowsAffected = command.ExecuteNonQuery();
}
catch (Exception ex)
{
// handle exception
}
finally
{
connection.Close();
}
}
僅供參考:我是「新手」我的數據庫被稱爲安裝程序。我已經手動添加了一個名爲myTable的表,其中有兩列userName,另一個名爲password,它們都設置在nchar(50)
變化'插入Setup'到'插入myTable' – MilkyWayJoe 2012-04-27 18:29:50
提示 - 這是更好的(較短)以例如使用'using(){}''使用(SqlConnection連接=新的SqlConnection(連接字符串)) connection.Open(); //在這裏工作;連接在下面一行關閉。 }' – sinelaw 2012-04-27 18:29:59