2014-07-02 55 views
-2

我收到以下錯誤:錯誤保存到數據庫的組合框

error : you have an error in your sql syntax.check the manual that corresponds to your mysql server version for the right syntax to use near 'SOFTWARE DEVELOPER' at line 1.

這是我的代碼:

Imports MySql.Data.MySqlClient 

Public Class Form2 

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click 

    Dim conStr As String = ("server=localhost;username=root;password=rootfnc;database=one") 
    Try 
     Dim con As New MySqlConnection(conStr) 
     Dim cmd As MySqlCommand 

     For i = 0 To ComboBox1.Items.Count 
      con.Open() 

      Dim sqls As String 
      sqls = "insert into one.initial_nom (idinitial_nom, f_name, s_name, th_name, fo_name, app_no, adm_type) values ('" & TextBox6.Text & "','" & TextBox1.Text & "', '" & TextBox2.Text & "', '" & TextBox3.Text & "', '" & TextBox4.Text & "', '" & TextBox5.Text & ",'" & ComboBox1.Items(i).ToString & "')" 
      cmd = New MySqlCommand(sqls, con) 
      cmd.ExecuteNonQuery() 
     Next 
    Catch ex As Exception 
     MsgBox("Error in saving to Database. Error is :" & ex.Message) 
    End Try 
End Sub 

有誰知道錯誤是怎麼引起的?

+0

請提供更多詳細信息。你什麼時候收到錯誤?你想做什麼?? – Blunderfest

+0

我想添加一些記錄與組合box.when我點擊保存按鈕...錯誤:你有一個錯誤在你的SQL syntax.check手冊,對應於你的mysql服務器版本的正確語法使用附近' SOFTWARE DEVELOPER'在第1行。 – user3795891

+0

在您的物品計數中,Items.Count-1 – Codexer

回答

1

您沒有正確封閉所有你插入撇號中字符串的值:

... '" & TextBox5.Text & "_,'" & ComboBox1.Items(i).ToString & "')" 

通知,我已經把下劃線,TextBox5.Text串接到後弦:應該有那裏有一個關閉的撇號,在逗號前。

現在,事實上,您不應該首先將用戶輸入的SQL命令連接在一起,而應該使用SqlCommandSqlParameter collection準備語句。這裏有一個簡化的例子:

sqls = "insert into tableName (column1) values (@parameterName)" 
cmd = New MySqlCommand(sqls, con) 
cmd.Parameters.Add(new MySqlParameter("@parameterName", TextBox5.Text)) 
' ... 
' <snip - set other parameters as needed> 
' ... 
cmd.ExecuteNonQuery() 
+0

Dang ticks,nice catch! – Codexer

+0

不錯,關於參數!非常感謝Dan J – user3795891