我有这段代码,但有一个我无法解决的问题。我想在if条件下访问我的SQL Server表,但一直告诉我必须声明变量@thisuser
。谁能帮我吗?
private void btnPersonalInfo_Click(object sender, EventArgs e)
{
sqlcon.Open();
string query = "SELECT score1, score2, score3 FROM tblLogin WHERE username = @thisuser";
SqlCommand sda = new SqlCommand(query, sqlcon);
SqlDataReader da = sda.ExecuteReader();
if (thisuser == da.GetValue(1).ToString())
{
while (da.Read())
{
MessageBox.Show("Your Personal Info are: sda.GetValue(3).ToString()");
}
}
sqlcon.Close();
}
答案 0 :(得分:4)
您忘记将参数添加到SqlCommand中。您命令不知道要为“ @thisuser”填写哪个值。
您可以添加如下参数:
sqlCommand.Parameters.Add("parameter_name", SqlDbType.TargetSqlType).Value = parameter_value;
所以您的代码应如下所示:
private void btnPersonalInfo_Click(object sender, EventArgs e)
{
var username = "foo bar";
sqlcon.Open();
string query = "SELECT score1, score2, score3 FROM tblLogin WHERE username = @thisuser";
SqlCommand sda = new SqlCommand(query, sqlcon);
sda.Parameters.Add("@thisuser", SqlDbType.NVarChar).Value = username;
SqlDataReader da = sda.ExecuteReader();
if (thisuser == da.GetValue(1).ToString())
{
while (da.Read())
{
MessageBox.Show("Your Personal Info are: sda.GetValue(3).ToString()");
}
}
sqlcon.Close();
}
感谢Larnu指出AddWithValue函数的一些问题。如果您使用AddWithValue-function而不是上面的Add-function,则类型转换将自动完成。这可能会导致问题。有关更多信息,请查看评论中的链接。
答案 1 :(得分:-1)
如果您只需要从SQL DB中选择值为'thisuser'的用户名,则需要将值放在单引号之间,因为这是正常的SQL字符串格式。
赞:
private void btnPersonalInfo_Click(object sender, EventArgs e)
{
sqlcon.Open();
string query = "SELECT score1, score2, score3 FROM tblLogin WHERE username = 'thisuser'";
SqlCommand sda = new SqlCommand(query, sqlcon);
SqlDataReader da = sda.ExecuteReader();
if (thisuser == da.GetValue(1).ToString())
{
while (da.Read())
{
MessageBox.Show("Your Personal Info are: sda.GetValue(3).ToString()");
}
}
sqlcon.Close();
}
如果您只需要从SQL DB中选择具有在C#代码中声明的值的用户名,则您需要这样编写查询字符串
private void btnPersonalInfo_Click(object sender, EventArgs e)
{
string thisuser = "example"; // example value
sqlcon.Open();
if (!string.IsNullOrEmpty(thisuser)){
string query = "SELECT score1,score2,score3 FROM tblLogin WHERE
username = '" + thisuser + "'";
SqlCommand sda = new SqlCommand(query, sqlcon);
SqlDataReader da = sda.ExecuteReader();
if (thisuser == da.GetValue(1).ToString())
{
while (da.Read())
{
MessageBox.Show("Your Personal Info are: sda.GetValue(3).ToString()");
}
}
}
sqlcon.Close();
}
答案 2 :(得分:-1)
您在内联查询中使用参数,但未传递参数