简体   繁体   中英

SQL, C# - Can't convert int32 to string?

Alright, so I have the following SQL query:

 query.CommandText = "SELECT FirstName, LastName, Age FROM Characters WHERE LastName LIKE   '"+name+"' ORDER BY Age";

And this loop that stores the result in the string "output"

while (reader.Read()) {
    output = output + reader.GetString(0) + reader.GetString(1) + reader.GetString(2).ToString();
}

However, for the third attribute age , which is an int, I get an error

could not convert System.Int32 to type System.String

As you see, I've already tried to solve this by using the int.ToString() function but I still get the same error. What am I doing wrong here? Thanks in advance!

reader.GetString(2).ToString() is pointless, it either is already a string or you use the wrong method. Since you've mentioned that it's an int use reader.GetInt32 :

string firstName = reader.GetString(0);
string larstName = reader.GetString(1);
int age = reader.GetInt32(2);
output = output + string.Format("{0}{1}{2}", firstName, lastName, age);

If the column Age is nullable you need to use IsDBNull first, you could also use an int? then:

int? age = null;
if(!reader.IsDBNull(2))
    age = reader.GetInt32(2);

If you want to access a field by it's name rather than via index, use GetOrdinal :

int ageIndex = reader.GetOrdinal("Age");
int? age = null;
if(!reader.IsDBNull(ageIndex))
    age = reader.GetInt32(ageIndex);

As an important aside, you're open for sql-injection here:

query.CommandText = @"SELECT FirstName, LastName, Age 
                      FROM Characters 
                      WHERE LastName LIKE '" + name + "' ORDER BY Age";

because you're concatenating the sql query. Instead use sql-parameters:

query.CommandText = @"SELECT FirstName, LastName, Age 
                      FROM Characters 
                      WHERE LastName LIKE '%' + @LastName + '%' 
                      ORDER BY Age";
query.Parameters.Add("@LastName", SqlDbType.NVarChar).Value = name;

(if you don't want to find also substrings you don't need to use LIKE , then you can use = )

agree with Tim but something like

reader[2].ToString();

may be more generic and less buggy if you change your select order.

following Tim Comment:

reader["Age"].ToString();

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