2015-02-23 68 views
-2

我有一個Web窗體,它從用戶獲取數據。用戶輸入值並點擊添加按鈕。我想將用戶輸入的值插入到數據庫中。但是當我運行該項目。
「的」關鍵字附近的不正確的語法:它提供了在cmd.ExecuteNonQuery();sql命令,executeNonQuery()

SQLEXCEPTION以下錯誤用戶代碼爲未處理。

什麼問題和如何解決這個問題?

查詢是:

insert into EMPLOYEES 
    (EMP_ID, 
    FIRST_NAME, 
    SECOND_NAME, 
    THIRD_NAME, 
    LAST_NAME, 
    GENDER, 
    DATE_OF_BIRTH, 
    PLACE_OF_BIRTH, 
    NATIONALITY, 
    PHONE_NUMBER, 
    DEPT_ID, 
    JOB_ID, 
    START_DATE) 
values 
    ('" + txtid.Text + "', 
    '" + txtFirst.Text + "', 
    '" + txtsecond.Text + "', 
    '" + txtthird.Text + "', 
    '" + txtlast.Text + "', 
    '" + s + "', 
    '" + txtdob.Text + "', 
    '" + txtPlace.Text + "', 
    '" + txtnat.Text + "', 
    '" + txtphone.Text + "', 
    '" + txtdep.Text + "', 
    '" + txtpos.Text + "', 
    '" + txtstart.Text + "') 
+0

請編輯查詢到的問題 – waka 2015-02-23 14:46:52

+2

我也建議使用參數化查詢。除了更安全之外,它也更容易,因爲您不必注意是否必須避開字符串。 – Dirk 2015-02-23 14:51:20

+4

您可能在SQL中找不到錯誤。從編碼的角度和安全角度來看,以這種方式構建SQL命令(字符串連接)是危險的。使用參數化查詢。 – THBBFT 2015-02-23 14:51:37

回答

4

你不應該串聯SQL語句一起 - 使用參數化查詢來避免SQL注入,而且語法錯誤。

這裏是你應該如何調整你的代碼:

string sql = @"INSERT INTO employees (emp_id,first_name, second_name , third_name , last_name , gender , date_of_birth , place_of_birth ,nationality , phone_number, dept_id , job_id , start_date) 
       VALUES(@emp_id,@first_name, @second_name , @third_name , @last_name , @gender , @date_of_birth , @place_of_birth ,@nationality , @phone_number, @dept_id , @job_id , @start_date)"; 
SqlCommand exeSQL = new SqlCommand(sql, cn); 
cn.Open(); 
cmd.Parameters.AddWithValue("@emp_id", txtid.Text); 
cmd.Parameters.AddWithValue("@first_name", txtFirst.Text); 
cmd.Parameters.AddWithValue("@second_name", txtsecond.Text); 
cmd.Parameters.AddWithValue("@third_name", txtthird.Text); 
cmd.Parameters.AddWithValue("@last_name", txtlast.Text); 
cmd.Parameters.AddWithValue("@gender", s); 
cmd.Parameters.AddWithValue("@date_of_birth", txtdob.Text); 
cmd.Parameters.AddWithValue("@place_of_birth", txtPlace.Text); 
cmd.Parameters.AddWithValue("@nationality", txtnat.Text); 
cmd.Parameters.AddWithValue("@phone_number", txtphone.Text); 
cmd.Parameters.AddWithValue("@dept_id", txtdep.Text); 
cmd.Parameters.AddWithValue("@job_id", txtpos.Text); 
cmd.Parameters.AddWithValue("@start_date", txtstart.Text); 
exeSQL.ExecuteNonQuery();