簡體   English   中英

是否需要.ExecuteNonQuery()才能將SQL數據添加到vb.net中的數據庫

[英]Is .ExecuteNonQuery() required to add sql data to a DB in vb.net

我正在運行以下代碼(部分代碼)以連接到PHPmyadmin DB

Private Sub sreg_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

        SqlConnection.ConnectionString = ServerString



        Try
            If SqlConnection.State = ConnectionState.Closed Then
                SqlConnection.Open()
                MsgBox("Successfully connected to MySQL DB")
            Else
                SqlConnection.Close()
                MsgBox("Connection is Closed")
            End If
        Catch ex As Exception
            MsgBox(ex.ToString)

        End Try
    End Sub

Public Sub SaveNames(ByRef SQLStatment As String)
        Dim cmd As MySqlCommand = New MySqlCommand

        With cmd
            .CommandText = SQLStatment
            .CommandType = CommandType.Text
            .Connection = SqlConnection
            .ExecuteNonQuery()
        End With

        SqlConnection.Close()
        MsgBox("Succesfully Added!")
        SqlConnection.Dispose()
    End Sub 

但是, .ExecuteNonQuery()在錯誤和問題方面讓我頭疼不已。 它上傳數據,但是只能返回一次(一次上傳),然后返回錯誤。

當我刪除.ExecuteNonQuery()沒有數據上傳嗎? 因此,我認為這是必要的。

這是我正在上傳的代碼(部分代碼)

 sql = "INSERT INTO students(student_id, title, initial, surname,
 street, city, pcode, country ) VALUES ('" & strStudent & "', '" 
 & vtital & "', '" & vinital & "', '" & vsurname & "', '" & vstreet 
 & "', '" & vcity & "', '" & vpcode & "', '" & vcountry & "' )"

 SaveNames(sql)

希望我的問題有道理,希望我能理解

嘗試這個 ...

cmd = New MySqlCommand( sqlstatement, conn)
conn.open()

cmd.ExecuteNonQuery()
conn.Close()

正如我建議你..使用參數化

保存此數據的方法中存在一些錯誤,可能會導致問題。
第一個問題是代碼不使用參數化查詢。 這是一個安全問題(Sql注入),但也是一個簡單的邏輯問題。 如果連接字符串以構建sql查詢,則字符串存在問題,該字符串包含對數據庫sql引擎具有特殊含義的字符。 如果您的字符串之一包含單引號怎么辦? 它會被視為字符串的結尾,而文本的其余部分將視為無效的sql。

第二個問題是在出現異常的情況下也缺少打開/關閉/釋放MySqlConnection的功能。 這可以通過使用Using語句解決。

所以我將您的方法重寫為

Public SaveNames(ByRef SQLStatment As String, List(Of MySqlParameter) parameters) As Integer
    Using con = new MySqlConnection(... put here the connection string...)
    Using cmd = New MySqlCommand(SQLStatment, con)
         if parameters.Count > 0 Then
            cmd.Parameters.AddRange(parameters.ToArray())
         End If
         return cmd.ExecuteNonQuery()
    End Using
    End Using
End Function

並用這樣的代碼調用它

sql = "INSERT INTO students(student_id, title, initial, surname," & _
      "street, city, pcode, country ) VALUES (@id,@title,@init,@sur," & _
      "@street,@city,@pcode,@country)"
Dim ps = New List(Of MySqlParameters)()
Dim p = new MySqlParameter("@id", MySqlDbType.Int32).Value = Convert.ToInt32(strStudent)
ps.Add(p)
p = new MySqlParameter("@title", MySqlDbType.VarChar).Value = vtital
ps.Add(p)
.. and so on for the other parameters. 
.. respecting the actual datatype on the database table
.....
SaveNames(sql, ps)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM