2017-03-28 24 views
1

我的代碼:在'NAME'附近預期條件的上下文中指定的非布爾類型的表達式。

string SqlSelectQuery = " Select * From [KTS MANAGMENT] Where STAFF NAME=" + Convert.ToString(textBox1.Text); 

SqlCommand cmd = new SqlCommand(SqlSelectQuery, CON); 
SqlDataReader dr = cmd.ExecuteReader(); 

我得到這個錯誤:

An expression of non-boolean type specified in a context where a condition is expected, near 'NAME'

+0

即時通訊新的在stackoverflow也即時只有初學者在現場,所以你可以只是建議我輕鬆不抱怨和喊 –

+0

如果你還沒有意識到它,問題是你的列名空間,你應該使用'[工作人員姓名] ,但是當然你也在代碼中缺少''',但你應該真的使用marc的代碼。 –

回答

1

你應該總是使用參數化查詢避免SQL注入 - 仍然在計算排名第一的漏洞。

因此,你的代碼應該是這樣的:

string connectionString = "......"; // typically read from config file 
string query = "SELECT * FROM [KTS MANAGMENT] WHERE STAFF NAME = @Name"; 

using (SqlConnection con = new SqlConnection(connectionString)) 
using (SqlCommand cmd = new SqlCommand(query, con) 
{ 
    cmd.Parameters.Add("@Name", SqlDbType.VarChar, 100).Value = textBox1.Text; 
    con.Open(); 

    using (SqlDataReader dr = cmd.ExecuteReader()) 
    { 
     // read the values from the SQL data reader.... 
    } 

    con.Close(); 
} 

這種方法還可以避免你有錯誤,在SQL語句中缺少的字串,和/或不匹配的單或雙引號...

+1

謝謝你的x_x太多.....你知道我正在做這個小項目(數據庫和界面),因爲3周,最後我覺得**我還活着** –

相關問題