用值从VB.NET连接到mySQL

时间:2015-11-09 11:25:27

标签: mysql vb.net

我正在尝试连接到mySql,但是我找错了我找错了。

我的表单包含一个标签,该标签是一个将发布到Score的数字和一个文本框,用户在其中输入要在Navn中发布的名称。

到目前为止我的代码是:

Imports System
Imports System.Data
Imports System.Data.SqlClient
Public Class Form1

    Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
        Dim connect As New SqlConnection("Data Source = mysqlAdress;Network Library= DBMSSOCN;Initial Catalog=**;User ID=**;Password=**;")
        Dim query As String = "INSERT INTO 2048 VALUES(@score, @name)"
        Dim command As New SqlCommand(query, connect)

        command.Parameters.Add("@score", SqlDbType.Int).Value = Label1.Text
        command.Parameters.Add("@navn", SqlDbType.VarChar).Value = TextBox1.Text
        connect.Open()
        connect.Close()
    End Sub

1 个答案:

答案 0 :(得分:2)

你的表名应该包含在这样的反引号中:

Dim query As String = "INSERT INTO `2048` VALUES(@score, @name)"

还尝试避免使用具有此类命名约定的表名,即。仅限数字。

您也在同时打开和关闭连接。

connect.Open()
connect.Close()

试试这样:

Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
    Dim connectionString As String = "Data Source = mysqlAdress;Network Library= DBMSSOCN;Initial Catalog=**;User ID=**;Password=**;"
    Using SQLConnection As New MySqlConnection(connectionString)
        Using sqlCommand As New MySqlCommand()
            With sqlCommand
                .CommandText = "INSERT INTO `2048` VALUES(@score, @name)"
                .Connection = SQLConnection
                .CommandType = CommandType.Text
                .Parameters.AddWithValue("@score", Label1.Text)
                .Parameters.AddWithValue("@name", TextBox1.Text)
            End With
            Try
                SQLConnection.Open()
                sqlCommand.ExecuteNonQuery()
            Catch ex As MySqlException
                MsgBox ex.Message.ToString
            Finally
                SQLConnection.Close()
            End Try
        End Using
    End Using 
End Sub