VB連接MYSQL實例
電腦需安裝數(shù)據(jù)庫'mysql server'和'mysql connector net'相關(guān)版本軟件。
在工程的‘項目’-‘添加引用’中添加引用‘mysql.data’
實現(xiàn)代碼如下: Imports System.IO Imports System Imports System.Data Imports System.Windows.Forms Imports MySql.Data.MySqlClient Public Class Form1 Dim conn As MySqlConnection Dim data As DataTable Dim da As MySqlDataAdapter Dim cb As MySqlCommandBuilder
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load If Not conn Is Nothing Then conn.Close() Dim connStr As String Dim reader As MySqlDataReader connStr = String.Format("server={0};user id={1}; password={2}; database=mysql; pooling=false", "localhost", "root", "root") '登錄mysql數(shù)據(jù)庫 為本機,用戶名:root 密碼:root Try conn = New MySqlConnection(connStr) conn.Open() reader = Nothing Dim cmd As New MySqlCommand("use db", conn) '進入存儲數(shù)據(jù)所用的數(shù)據(jù)庫 reader = cmd.ExecuteReader() While (reader.Read()) End While If Not reader Is Nothing Then reader.Close() Catch ex As MySqlException 'MessageBox.Show(ex.ToString) MessageBox.Show("程序出現(xiàn)錯誤!請重啟,或聯(lián)系維護人員。", "抱歉") Finally If Not reader Is Nothing Then reader.Close() End Try
End Sub
Private Sub btnconn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnconn.Click Dim temp_int, int_lrow, int_rrow As Integer
data = New DataTable Try da = New MySqlDataAdapter("select * from db_table where name='lady_gaga'", conn) '在相關(guān)表中查找數(shù)據(jù) db_table 為表名,name 為列名 cb = New MySqlCommandBuilder(da)
da.Fill(data) int_rrow = data.Rows.Count '返回查找后的數(shù)據(jù)行數(shù),返回0行則表示沒有找到記錄,返回大于0行,則表示找到了相關(guān)記錄 If int_rrow = 0 Then MessageBox.Show("無記錄") Else MessageBox.Show("data.Rows.Item(0).Item(3).ToString") 'Item(0).Item(3) 表示返回的第1條記錄(第一條的下標(biāo)為0)中的第4列值 End If
Catch ex As Exception MessageBox.Show(ex.ToString) End Try End Sub End Class
|