数据库-使用DataReader的简单实例(两种办法)

ADO.NET包含两种类库:

  1. SQLOLEDB
  2. SQL

程序界面

程序清单

 

 1 Imports System.Data
 2 Imports System.Data.OleDb
 3 Imports System.Data.SqlClient
 4 Public Class Form1
 5     Dim strConnect As String = "Provider=SQLOLEDB.1;Integrated Security=SSPI;Persist Security Info=False;Initial Catalog=lzTest;Data Source=SVCTAG-4T7582X" '连接字符串编写借助了udl文件
 6 
 7     Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
 8         '使用SQLOLEDB方式
 9         '连接对象是OleDBConnection对象
10         'Command对象是OleDBCommand对象
11         'DataReader对象是OleDBDataReader对象
12         Dim myConnect As New OleDbConnection()
13         myConnect.ConnectionString = strConnect
14         Try
15             myConnect.Open() '打开数据库
16             Dim myCommand As New OleDbCommand("select * from employees", myConnect) '打开表
17             Dim myDataReader As OleDbDataReader
18             myDataReader = myCommand.ExecuteReader()
19             ListBox1.Items.Clear()
20             While (myDataReader.Read())
21                 ListBox1.Items.Add(myDataReader.GetString(1)) 'ps:姓名列是第二列,列序号从0开始,所以这里填1
22             End While
23         Catch ex As Exception
24             MsgBox(ex.ToString(), MsgBoxStyle.AbortRetryIgnore, "出现异常")
25         Finally
26             If myConnect.State = ConnectionState.Open Then
27                 myConnect.Close()
28             End If
29         End Try
30     End Sub
31 
32     Dim strConn2 As String = "server=SVCTAG-4T7582X;Integrated Security=SSPI;Persist Security Info=False;database=lzTest"
33 
34     Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
35         '使用SqlConnection类库,需要先引入System.data.SqlClient
36         'PS: 连接字符串不需要Provider值,其他关键字也不同
37         '连接对象是SQLConnection对象
38         'Command对象是SQLCommand对象
39         'DataReader对象是SQLDataReader对象
40         Dim myConn As SqlConnection = New SqlConnection()
41         myConn.ConnectionString = strConn2
42         Try
43             myConn.Open()
44             Dim command1 As SqlCommand = New SqlCommand("select * from employees", myConn)
45             Dim DataReader1 As SqlDataReader
46             DataReader1 = command1.ExecuteReader()
47             ListBox1.Items.Clear()
48             While (DataReader1.Read())
49                 ListBox1.Items.Add(DataReader1.GetValue(1).ToString())
50             End While
51         Catch ex As Exception
52             MsgBox(ex.ToString())
53         Finally
54             If myConn.State = ConnectionState.Open Then
55                 myConn.Close()
56             End If
57         End Try
58     End Sub
59 End Class
60 

 

 

 

 

posted @ 2008-09-08 16:45  怒杀神  阅读(366)  评论(0编辑  收藏  举报