查询语句的问题
SqlCommand cmd = new SqlCommand( "select column from table1 where .... ",sqlConnection1)
sqlConnection1.Open();
string column1=(string)cmd.ExecuteScalar();
sqlConnection1.Close();
这个查询语句是要查找表中的某一个字段的值,如果没有该字段的值为空时,cmd.ExecuteScalar()一句就会出错:末将对象应用到对象的实例.
在不知道查询的结果是否为空时,怎样避免这种错误的发生.
应该用哪个execute...
------解决方案--------------------object obj=cmd.ExecuteScalar();
if(obj==Null||obj==DBNull.value)
{
column1= " ";
}
else
{
column1=...
}
==============================
这个蛮好
------解决方案--------------------string column1=Convert.ToString(cmd.ExecuteScalar());
这样应该是可以的
------解决方案--------------------报错?我怎么不报错...
private void button1_Click(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection();
conn.ConnectionString = "server=.;uid=sa ";
conn.Open();
SqlCommand cmd = new SqlCommand( "select 1 where 1=2 ", conn);
string a = cmd.ExecuteScalar() + " ";
MessageBox.Show(a);
}