VB.Net:SQL检查现有值

时间:2015-05-21 01:15:03

标签: mysql sql vb.net

我有这段代码要求用户选择用户名:

Dim name As String = InputBox("Input your Username. 15 Characters or Less in Length.", "Choose a Username", "")
Dim chosenName As String = name.ToUpper

此代码将其添加到我的数据库phpmyadmin:

Dim SQLStatement As String = "INSERT INTO usernames(username) VALUES('" & chosenName & "')"
saveUsernames(SQLStatement)

要搜索的任何代码以检查数据库中是否已经使用了用户名吗?

数据库结构: 表名:"usernames"

columbs:"id""username"

请离开:

Imports MySql.Data.MySqlClient

Dim serverString As String = "Database=sql477993;Data Source=sql4.freemysqlhosting.net;User Id=sql477993;Password=cF5%gB2*"
Dim SQLConnection As MySqlConnection = New MySqlConnection

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
SQLConnection.ConnectionString = serverString
If SQLConnection.State = ConnectionState.Closed Then
SQLConnection.Open()
MsgBox("Connected")
Else
SQLConnection.Close()
MsgBox("Closed")
End If
End Sub

Public Sub saveUsernames(ByRef SQLStatement As String)
Dim cmd As MySqlCommand = New MySqlCommand
With cmd
.CommandText = SQLStatement
.CommandType = CommandType.Text
.Connection = SQLConnection
.ExecuteNonQuery()
End With
SQLConnection.Close()
MsgBox("Saved")
SQLConnection.Dispose()
End Sub

Dim SQLStatement As String = "INSERT INTO usernames(username) VALUES('" & chosenName & "')"
saveUsernames(SQLStatement)

2 个答案:

答案 0 :(得分:0)

在所有示例中,我忽略了输入中的字符串构建。

如果你想在进行插入的同时进行检查,并且如果它已经存在则可以默认为你可以修改你的sqlstatement只插入它尚不存在的位置:

INSERT INTO usernames(username) 
SELECT chosenName 
 WHERE NOT EXISTS(SELECT 1 FROM usernames WHERE username = chosenName)

但这可能不是你想要的,因为通常你会想要提供反馈。

对于反馈,您可以检查单独语句的结果并在VB代码中处理查询结果:

SELECT CASE 
         WHEN EXISTS(SELECT 1 FROM usernames WHERE username = chosenName)
         THEN 1
         ELSE 0
       END userNameExists

这里的缺点是对数据库的额外往返。

为了避免你可以选择从单个sql中抛出一个错误,如果它已经存在:

IF EXISTS(SELECT 1 FROM usernames WHERE username = chosenName)
   RAISERROR --look up this syntax
INSERT INTO usernames(username) VALUES (chosenName)

为了清晰起见,你可以有一个ELSE,但为了简洁起见,我把它留了下来。在这种情况下需要它,因为错误将触发或代码将继续。

msdn raiserror

编辑:raiseerror ref用于mssql。你需要检查mssql中的等价物。

答案 1 :(得分:0)

最好使用文本框而不是输入框,所以这样使用>>> txtUsername.Text将是输入。

Imports System.Data
Imports MySql.Data.MySqlClient

Dim chosenName as String = txtUsername.Text.toUpper()
Private Sub frmMenu_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
    Connect()
End Sub

添加SAVE按钮:

Private Sub cmdSave_Click(ByVal sender As System.Object, _
                    ByVal e As System.EventArgs) Handles cmdRegister.Click
            If con.State = ConnectionState.Open Then
                con.Close()
            End If
            con.Open()
            query = "select username from usernames where username = ?"
            command = New MySqlCommand(query, con)
            command.Parameters.Add(New MySqlParameter("username", chosenName)
            reader = command.ExecuteReader()

            If reader.HasRows Then 'username already exists
                MessageBox.Show("Username already exists.", "Invalid Input!", _
                        MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
                With txtUsername
                      .Clear() 'clears the textbox
                      .Focus() 'focused cursor to the textbox
                End With
            Else 'username is available
                query = "INSERT INTO usernames(username) VALUES(@username)"
                params = {"username"}
                values = {"" & chosenName}

                SaveUpdateDelete(query, params, values)
                MessageBox.Show("Username successfully saved!", "SAVED!", _
                           MessageBoxButtons.OK, MessageBoxIcon.Information)
           End if
End Sub

con有你的联系,你可以在module

中加入
Public Sub Connect()
    serverString = "Database=sql477993;Data Source=sql4.freemysqlhosting.net;User Id=sql477993;Password=cF5%gB2*"
    con.ConnectionString = serverString
    If Not con.State = ConnectionState.Open Then
        con.Open()
    End If
End Sub

Public Sub SaveUpdateDelete(ByVal sql As String, ByVal parameters() As String, _
 ByVal Values() As String)
    If con.State = ConnectionState.Open Then
        con.Close()
    End If
    con.Open()
    command = New MySqlCommand(sql, con)

    For i = 0 To parameters.Count - 1
        command.Parameters.AddWithValue("@" & parameters(i).ToString, Values(i))
    Next
    command.CommandText = sql
    command.ExecuteNonQuery()

    con.Close()
End Sub

在任何地方声明这些变量,但最好是在模块中声明这些变量以便能够以不同的形式重用这些变量。

Imports System.Data
Imports MySql.Data.MySqlClient

Public con As New MySqlConnection
Public query As String
Public command As MySqlCommand
Public reader As MySqlDataReader
Public serverString as String