VB连接MYSQL实例
电脑需安装数据库'mysql server'和'mysql connector net'相关版本软件。
在工程的‘项目’-‘添加引用’中添加引用‘mysql.data’
实现代码如下:
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数据库 为本机,用户名:root 密码:root
Try
conn = New MySqlConnection(connStr)
conn.Open()
reader = Nothing
Dim cmd As New MySqlCommand("use db", conn) '进入存储数据所用的数据库
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("程序出现错误!请重启,或联系维护人员。", "抱歉")
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) '在相关表中查找数据 db_table 为表名,name 为列名
cb = New MySqlCommandBuilder(da)
da.Fill(data)
int_rrow = data.Rows.Count '返回查找后的数据行数,返回0行则表示没有找到记录,返回大于0行,则表示找到了相关记录
If int_rrow = 0 Then
MessageBox.Show("无记录")
Else
MessageBox.Show("data.Rows.Item(0).Item(3).ToString") 'Item(0).Item(3) 表示返回的第1条记录(第一条的下标为0)中的第4列值
End If
Catch ex As Exception
MessageBox.Show(ex.ToString)
End Try
End Sub
End Class