SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["connecton1"].ConnectionString);
conn.Open();
SqlCommand check = new SqlCommand("SELECT Location FROM Items WHERE Serial="+Convert.ToInt32(Serialtxt.Text).ToString()+"", conn);
string checker = check.ExecuteReader();
我正在尝试在我的数据库中查找一段数据并将其分配给变量。我得到的错误是
无法将类型'System.Data.SqlClient.SqlDataReader'隐式转换为字符串
我做错了什么?
答案 0 :(得分:5)
您必须改为使用ExecuteScalar
。
string checker = (string)check.ExecuteScalar();
您还应该使用sql-parameters来阻止sql-injection。
SqlCommand check = new SqlCommand("SELECT Location FROM Items WHERE Serial = @Serial", conn);
check.Parameters.AddWithValue("@Serial", Convert.ToInt32(Serialtxt.Text));
如果您希望每个序列有多行,则可以使用ExecuteReader
并填写List<string>
:
List<string> allLocations = new List<string>();
using(SqlDataReader rd = check.ExecuteReader())
while(rd.Read())
allLocations.Add(rd.GetString(0));
答案 1 :(得分:1)
将检查器类型从string
更改为SqlDataReader
然后你可以做
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["connecton1"].ConnectionString);
conn.Open();
SqlCommand check = new SqlCommand("SELECT Location FROM Items WHERE Serial ="+Convert.ToInt32(Serialtxt.Text).ToString()+"", conn);
SqlDataReader checker = check.ExecuteReader();
while (checker.Read())
{
if (checker[0] != null)
{
//some logic with the result
}
}