我怎样才能在vb.net中修复我的数据库连接?

时间:2013-09-20 06:58:19

标签: mysql vb.net database-connection

    Imports MySql.Data.MySqlClient
    Imports MySql.Data
    Public Class Form1
    Dim dbcon As New MySqlConnection("Data Source=VINCENT-PC\SQLEXPRESS;Initial Catalog=Group1;Integrated Security=True")
    Dim sqlcmd As String
    Dim mysqlcmd As MySqlCommand
    Dim dr As MySqlDataReader

Private Sub btnSearch_Click(sender As System.Object, e As System.EventArgs) Handles btnSearch.Click
    Try
        sqlcmd = "Select * from Sample1 where num=" + txtname.Text
        mysqlcmd = New MySqlCommand(sqlcmd, dbcon)
        dbcon.Open()
        dr = mysqlcmd.ExecuteReader
        While dr.Read
            txtfname = dr.Item("fname")
            txtlname = dr.Item("lname")
        End While
        dr.Close()
        dbcon.Close()
    Catch ex As Exception
        MsgBox("Error: " & vbCrLf & vbCrLf & vbCrLf & ex.Message)
    End Try
End Sub
    End Class

这是我写的代码,但似乎它没有连接到我的数据库请帮助我并提前感谢

1 个答案:

答案 0 :(得分:0)

请尝试以下代码:

Imports System.Data.SqlClient

Dim Conn As SqlConnection
Dim sqlcmd As String
Dim mysqlcmd As SqlCommand
Dim dr As SqlDataReader

Private Sub btnSearch_Click(sender As System.Object, e As System.EventArgs) Handles btnSearch.Click
dim m_CurrConstr as String 
dim m_svrname as String 
dim m_Currentdbf as String
m_Srvname="VINCENT-PC\SQLEXPRESS"
m_Currentdbf ="[YourDBName]"
    Try
        m_CurrConStr = "Server=" & m_Srvname & ";Initial Catalog=" & m_Currentdbf & ";User ID=sa;Password=as;Trusted_Connection=False;"
        Conn = new Sqlconnection(m_currConstr)
        sqlcmd = "Select * from Sample1 where num=" + txtname.Text
        mysqlcmd = New SqlCommand(sqlcmd, Connn)
        Conn.Open()
        dr = mysqlcmd.ExecuteReader
        While dr.Read
            txtfname = dr.Item("fname")
            txtlname = dr.Item("lname")
        End While
        dr.Close()
        Conn.Close()
    Catch ex As Exception
        Messagebox.Show("Error: " & vbCrLf & vbCrLf & vbCrLf & ex.Message)
    End Try
End Sub

如果我回答了你的问题,请标记为答案