[英]Whats wrong with my select statment?
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();
I'm trying to look for a piece of data in my database and assign it to a variable. 我正在尝试在数据库中查找数据并将其分配给变量。 The error I get is
我得到的错误是
Cannot implicitly convert type 'System.Data.SqlClient.SqlDataReader' to string
无法将类型'System.Data.SqlClient.SqlDataReader'隐式转换为字符串
What am I doing wrong? 我究竟做错了什么?
You have to use ExecuteScalar
instead. 您必须改为使用
ExecuteScalar
。
string checker = (string)check.ExecuteScalar();
You should also use sql-parameters to prevent sql-injection. 您还应该使用sql-parameters防止sql-injection。
SqlCommand check = new SqlCommand("SELECT Location FROM Items WHERE Serial = @Serial", conn);
check.Parameters.AddWithValue("@Serial", Convert.ToInt32(Serialtxt.Text));
If you instead expect multiple rows per serial you can use ExecuteReader
and fill a List<string>
: 如果您希望每个序列有多个行,则可以使用
ExecuteReader
并填充List<string>
:
List<string> allLocations = new List<string>();
using(SqlDataReader rd = check.ExecuteReader())
while(rd.Read())
allLocations.Add(rd.GetString(0));
change the checker type from string
to SqlDataReader
将检查器类型从
string
更改为SqlDataReader
then you could do 那你可以做
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
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.