每次我尝试连接数据库时都会出现此错误:
The ConnectionString property has not been initialized
我该怎么做才能解决这个问题?
以下是我的代码:
private void OKButton_Click(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection();
conn.ConnectionString = "Data Source = ; Initial Catalog = ; USER ID = ; PASSWORD = ;";
string sql = (@"INSERT INTO (1, 2, 3) VALUES('"+1b.Text+"', '"+2b.Text+"','"+3b.Text+"');");
SqlCommand cmd = new SqlCommand(sql, conn);
cmd.Parameters.AddWithValue("@1", 1b.Text);
cmd.Parameters.AddWithValue("@2", 2b.Text);
cmd.Parameters.AddWithValue("@3", 3b.Text);
conn.Open();
cmd.Connection = conn;
cmd.ExecuteNonQuery();
conn.Close();
}
private void CloseButton_Click(object sender, EventArgs e)
{
Close(); //<---ExecuteNonQuery error in here
}
答案 0 :(得分:0)
将sql命令更改为以下格式:
//查看如何使用参数
string sql = @“INSERT INTO TableName(col1,col2,col3)VALUES(@ p1,@ p2,@ p3);
SqlCommand cmd = new SqlCommand(sql,conn);
cmd.Parameters.AddWithValue(“@ p1”,1b.Text);
cmd.Parameters.AddWithValue(“@ p2”,2b.Text);
cmd.Parameters.AddWithValue(“@ p3”,3b.Text);