use*_*517 0 c# sql database forms
有人可以告诉我为什么这不是将值添加到数据库中.表单运行正常,不会返回任何错误.
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();
}
}
Run Code Online (Sandbox Code Playgroud)
仅供参考:我是"新手"我的数据库名为Setup.我手动添加了一个名为myTable的表,其中包含2列userName,另一个名为password,两者都设置为nchar(50)
您需要指定Table,而不是数据库(在连接字符串中使用).在表名中添加了模式前缀:
command.CommandText = "INSERT INTO dbo.myTable (userName, password) VALUES (@userName, @passWord)";
Run Code Online (Sandbox Code Playgroud)
并添加:
command.Connection = connection;
Run Code Online (Sandbox Code Playgroud)
将Command对象与连接对象关联.