2014-04-16 136 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一種可以放入字符串。