2014-04-16 135 views
2

以下是代码:输入字符串错误

string checkuser = "select * from [User] where UserName='" + txtusername.Text + "'"; 
SqlCommand com = new SqlCommand(checkuser, con); 
int temp = Convert.ToInt32(com.ExecuteScalar().ToString()); 
con.Close(); 
if (temp == 1) 

问题:

每当我运行下面的代码它给出错误输入字符串的不正确的格式

+2

这将是错误的转换为int。该命令将返回所有字段中的所有文本。然后,您将尝试将所有这些文本转换为失败的整数。你可以改变SQL查询来使用“select count(*)from ...”,然后这应该工作。 –

+0

你打算在'temp'中储存什么? – StevieB

回答

3

尝试

string checkuser = "select count(*) from [User] where [email protected]"; 

你的问题是ExecuteScalar返回第一行,结果第一列的值,它不能转换为整数

,如果您有编号列,例如age ,做如下

string checkuser = "select age from [User] where [email protected]"; 

SQL语句广泛开放的SQL注入攻击,你最好使用参数

string sql= "select count(*) from [User] where UserName = @UserName"; 
using(SqlConnection con = new SqlConnection(conString)) 
using(SqlCommand cmd= new SqlCommand(sql, con)) 
{ 
    con.Open(); 
    cmd.Parameters.AddWithValue("@UserName", txtusername.Text); 
    int temp = Convert.ToInt32(cmd.ExecuteScalar().ToString()); 
    if(temp == 1) 
    {} 
} 
+1

+1请注意关于SQL注入以及... –

1

ExecuteScalar返回第一行第一列的查询结果。看起来像你的com.ExecuteScalar().ToString()不是一个有效的整数,这就是为什么你得到这个错误。

如果你要计算你的查询,你需要使用SELECT COUNT(*),而不是SELECT *

并请使用parameterized queries。这种字符串连接对于SQL Injection攻击是开放的。

同样使用using statement来配置你的SqlConnectionSqlCommand;你

using(SqlConnection con = new SqlConnection(strConnString)) 
using(SqlCommand com = con.CreateCommand()) 
{ 
    string checkuser = "select COUNT(*) from [User] where UserName = @user"; 
    com.CommandText = checkuser; 
    com.Parameters.AddWithValue("@user", txtusername.Text); 
    int temp = (int)com.ExecuteScalar(); 
    if(temp == 1) 
    /// 
} 

也可以使用ExecuteScalar用于获取与specifiying列中的特定列值的第一行中的查询像SELECT columnname from [User]...

0

您应该返回标量值。但是,在您的查询中,您将返回result set,这不是兼容String类型。

所以,修改查询,如下所示:只有

string checkuser = "select count(*) from [User] where UserName='" + txtusername.Text + "'"; 

以上回报single value一种可以放入字符串。