简体   繁体   中英

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

What am I doing wrong?

You have to use ExecuteScalar instead.

string checker = (string)check.ExecuteScalar();

You should also use sql-parameters to prevent 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> :

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

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
           }
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM