SqlConnection cn = new SqlConnection(@"DataSource=dbedu.cs.vsb.cz\SQLDB;Persist Security Info=True;User ID=*****;Password=*******");
SqlCommand cmd = new SqlCommand();
string finish = DropDownListFi.SelectedValue;
cn.Open();
String Name = Request.QueryString["Name"];
cmd.CommandText = "UPDATE navaznost_ukolu SET finish=@finish where Name='" + Name + "'";
cmd.Parameters.Add(new SqlParameter("@finish", finish));
cmd.ExecuteNonQuery();
cmd.Clone();
错误消息
尚未初始化Executenonquery连接属性。
答案 0 :(得分:3)
您当前代码的问题在于您尚未设置Connection
对象的SqlCommand
属性。试试这个,
SqlCommand cmd = new SqlCommand();
cmd.Connection = cn;
您还必须参数化name
String Name = Request.QueryString["Name"];
cmd.CommandText = "UPDATE navaznost_ukolu SET finish=@finish where Name=@name";
cmd.Parameters.Add(new SqlParameter("@finish", finish));
cmd.Parameters.Add(new SqlParameter("@name", Name));
完整代码
string finish = DropDownListFi.SelectedValue;
String Name = Request.QueryString["Name"];
string connStr = @"DataSource=dbedu.cs.vsb.cz\SQLDB;
Persist Security Info=True;
User ID=*****;
Password=*******";
string sqlStatement = @"UPDATE navaznost_ukolu
SET finish = @finish
WHERE Name = @Name";
using (SqlConnection conn = new SqlConnection(connStr))
{
using(SqlCommand cmd = new SqlCommand())
{
cmd.Connection = conn;
cmd.CommandText = sqlStatement;
cmd.CommandType = CommandType.Text;
cmd.Parameters.Add(new SqlParameter("@finish", finish));
cmd.Parameters.Add(new SqlParameter("@name", Name));
try
{
conn.Open();
cmd.ExecuteNonQuery();
}
catch(SqlException e)
{
// do something with the exception
// do not hide it
// e.Message.ToString()
}
}
}
正确编码
using
语句进行propr对象处理try-catch
块来正确处理对象答案 1 :(得分:2)
错误是不言自明的,您尚未分配与命令的连接。您可以使用构造函数:
using(var cn = new SqlConnection(@"DataSource=dbedu.cs.vsb.cz\SQLDB;Persist Security Info=True;User ID=*****;Password=*******"))
using(var cmd = new SqlCommand(
"UPDATE navaznost_ukolu SET finish=@finish where Name=@Name"
, cn))
{
string finish = DropDownListFi.SelectedValue;
cn.Open();
String Name = Request.QueryString["Name"];
cmd.Parameters.AddWithValue("@finish", finish);
cmd.Parameters.AddWithValue("@Name", Name);
cmd.ExecuteNonQuery();
}
请注意,我还为Name
和using
语句使用了sql参数,以确保实现IDisposable
的任何内容都被处理掉,即使出现异常也是如此。这也将关闭连接。