1. 连接数据库
1)下载Connector/Net:
2)安装Connector/Net.
3)在VB.net工程中,选择Project->Add Reference…菜单,添加MySQl.data引用,如下图所示:
4) 在需要连接数据的文件中添加一行,以打开namespace:
Imports MySql.data.MySqlClient
5) 创建一个数据库连接
m_strConnection ="server=127.0.0.1;uid=root;pwd=12345;database=computer; pooling=false"
m_SqlConn = New MySqlConnection(m_strConnection)
2. 显示数据
1) 创建一个数据库适配器
Dim strQuery As String = "select * from Product"
Dim daAdapter As MySqlDataAdapter = New MySqlDataAdapter(strQuery, m_SqlConn)
2) 创建一个Datatable,用数据库适配器来填充datatable
Dim dsTable As DataTable = New DataTable(strDataset)
daAdapter.Fill(dsTable)
3) 绑定datatable到DataGrid控件
dbGridShow.SetDataBinding(dsTable, "")
dbGridShow.Visible = True
3. 获取表中的某一行某一列
‘获得指定行
Dim CurRow As Integer
CurRow = dbGridShow.CurrentRowIndex
Dim tbl As DataTable = dbGridShow.DataSource
Dim Row As DataRow = tbl.DefaultView(CurRow).Row
'根据当前选定的行得到Delete操作的SQL语句
Dim strDelete As String
strDelete = "delete from T_Bars where name = '" + Row("name") + "'"
4. 修改或删除数据
'定义操作的SQL语句
Dim strSql As String
strSql = "insert into Product(maker,model,type) values('"…”)
'创建SqlCommand对象
Dim myCommand As MySqlCommand = New MySqlCommand(strInsertCommand, m_SqlConn)
‘执行操作
m_SqlConn.Open()
nRows = myCommand.ExecuteNonQuery()