先来一个简单的实例。
VB.NET 2012
SQl server 2012
Access文件:http://download.csdn.Net/detail/dzweather/5042992
(两个版本,2003,2012,任选一个)
根据前面ADO.net入门的介绍,我们知道了连接的过程。
AccessFile文件,针对的是Oledb,所以首先应引用。
然后 ,定义三个对象,在实例中再进行创建(这样可以节约点资源)
特别注意 的是,里面没有了cmd过程,我感觉这样的入门适合我学习。
这个例子,就一个窗体,一个datagridview(不绑定,用代码绑定),然后就是几句代码,很简单。
[vb] view plain copy
print?
- Imports System.Data.OleDb
-
- Public Class Form1
- Dim cn As OleDbConnection
- Dim da As OleDbDataAdapter
- Dim ds As DataSet
-
- Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
- Dim cnStr As String = "rovider=Microsoft.Jet.OLEDB.4.0;Data Source=D:\persons.mdbersist Security Info=False"
- cn = New OleDbConnection(cnStr)
- Dim sql As String = "select * from grade"
- da = New OleDbDataAdapter(sql, cn)
- ds = New DataSet
- da.Fill(ds, "grade")
- DataGridView1.DataSource = ds.Tables(0)
- End Sub
- End Class
==========================================================================================================
上面的有点简单,但流程清晰。与我们实际应用有很大距离。
下面再跨一步,接近实际应用,即变得较为灵活点:
[vb] view plain copy
print?
- Imports System.Data.OleDb
-
- Public Class Form1
- Dim cn As OleDbConnection
- Dim da As OleDbDataAdapter
- Dim ds As DataSet
-
- Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
- Dim cnStr As String = "rovider=Microsoft.Jet.OLEDB.4.0;Data Source=D:\persons.mdbersist Security Info=False"
- cn = New OleDbConnection(cnStr)
- Dim sql As String = "select * from grade"
- da = New OleDbDataAdapter(sql, cn)
- ds = New DataSet
- da.Fill(ds, "grade")
- DataGridView1.DataSource = ds.Tables(0)
- End Sub
-
- Private Sub btnQuery_Click(sender As Object, e As EventArgs) Handles btnQuery.Click
- Dim cnStr As String = "rovider=Microsoft.Jet.OLEDB.4.0;Data Source=D:\persons.mdbersist Security Info=False"
- cn = New OleDbConnection(cnStr)
- Dim sql As String = TextBox1.Text
- da = New OleDbDataAdapter(sql, cn)
- ds = New DataSet
- da.Fill(ds, "grade")
- DataGridView1.DataSource = ds.Tables(0)
- End Sub
-
- Private Sub btnQueyName_Click(sender As Object, e As EventArgs) Handles btnQueyName.Click
- Dim cnStr As String = "rovider=Microsoft.Jet.OLEDB.4.0;Data Source=D:\persons.mdbersist Security Info=False"
- cn = New OleDbConnection(cnStr)
- Dim sql As String = "select * from grade where 姓名 like " & "'%" & TextBox2.Text & "%'"
- da = New OleDbDataAdapter(sql, cn)
- ds = New DataSet
- da.Fill(ds, "grade")
- DataGridView1.DataSource = ds.Tables(0)
- End Sub
- End Class
代码活没用try catch,反正只是入门。
结果如下:
这样就可以有两个查询方式,一是SQL语句灵活用,二是姓名。
这样一个简单的查询就出来了。这只是一个“查询”,但我们有时还要修改、删除等工作。
在修改,删除时,不但要执行SQL,最终我们还要把结果反馈给用户看。于是就有了第个简单实例。
========================================================================================================
DataGrideView控件,很多选项都是边框、单元颜色、数据格式、选择方式。太多了。画个图加深印象: