我正在尝试在标签中显示SQL查询结果,但它没有显示。这是我的代码:
string result = "SELECT ACTIVE FROM [dbo].[test] WHERE ID = '" + ID.Text + "' ";
SqlCommand showresult = new SqlCommand(result, conn);
conn.Open();
showresult.ExecuteNonQuery();
string actresult = ((string)showresult.ExecuteScalar());
ResultLabel.Text = actresult;
conn.Close();
请帮助。谢谢!
答案 0 :(得分:9)
试试这个。
string result = "SELECT ACTIVE FROM [dbo].[test] WHERE ID = '" + ID.Text + "' ";
SqlCommand showresult = new SqlCommand(result, conn);
conn.Open();
ResultLabel.Text = showresult.ExecuteScalar().ToString();
conn.Close();
答案 1 :(得分:1)
那里有拼写错误吗?您有两次对数据库的调用:
showresult.ExecuteNonQuery();
这不会返回值,我不确定为什么你会有它
string actresult = ((string)shresult.ExecuteScalar());
除非你有一个shresult变量,否则这个查询应该出错。什么是shresult变量?
答案 2 :(得分:1)
使用SqlParameter
过滤结果并调用ExecuteScalar()
或ExecuteReader()
方法。
string result = "SELECT ACTIVE FROM [dbo].[test] WHERE ID=@ID";
SqlCommand showresult = new SqlCommand(result, conn);
// If ID is int type
showresult.Parameters.Add("@ID",SqlDbType.Int).Value=ID.Txt;
// If ID is Varchar then
//showresult.Parameters.Add("@ID",SqlDbType.VarChar,10).Value=ID.Txt;
conn.Open();
string actresult = (string)showresult.ExecuteScalar();
conn.Close();
if(!string.IsNullOrEmpty(actresult))
ResultLabel.Text = actresult;
else
ResultLabel.Text="Not found";
答案 3 :(得分:1)
using (SqlConnection conn = new SqlConnection(connectionString))
{
string result = "SELECT ACTIVE FROM [dbo].[test] WHERE ID = @id";
SqlCommand showresult = new SqlCommand(result, conn);
showresult.Parameters.AddWithValue("id", ID.Text);
conn.Open();
ResultLabel.Text = showresult.ExecuteScalar().ToString();
conn.Close();
}
这将处理连接,并且在查询中没有字符串连接。
答案 4 :(得分:0)
conn.Open();
string result = "SELECT ACTIVE FROM test WHERE ID = '" + ID.Text + "' ";
SqlCommand showresult = new SqlCommand(result, conn);
showresult.ExecuteNonQuery();
int actresult = ((int)showresult.ExecuteScalar());
ResultLabel.Text = actresult.Tostring();
conn.Close();