要撰寫資料庫程式,需要告訴電腦我們現在要去哪台電腦中的資料庫的哪個資料表,
若需要帳號密碼(視資料庫平台需要)時,帳號密碼又是什麼.....等等.這些相關資
訊會組合成一串規定好的文字串,一般俗稱連結字串。譬如下面抓取微軟SQL SERVER
為例所示:
Dim connectionString as String="Data Source=IP位置;Initial Catalog=資料庫名稱;User ID=使用者帳號;Password=使用者密碼;Connect Timeout=timout時間"
不過這樣長的字串,記憶不易又容易打錯。如果透過 ConnectionStringBuilde 系列的類別,可以解決您這樣的困擾,目前微軟提供了
System.Data.SqlClient.SqlConnectionStringBuilder
System.Data.OleDb.OleDbConnectionStringBuilder
System.Data.Odbc.OdbcConnectionStringBuilder
System.Data.OracleClient.OracleConnectionStringBuilder
下面舉出使用Access 和 SQL Server 的例子:
' 撈取 SQL Server 資料
Imports System.Data.SqlClient
Sub getSqlData()
Dim sqlConnectionSB As SqlConnectionStringBuilder = New SqlConnectionStringBuilder()
Dim con As New SqlConnection
Dim cmd As New SqlCommand
With sqlConnectionSB
.DataSource = "IP"
.InitialCatalog = "資料庫名稱" 'EX:172.17.1.15
.UserID = "帳號"
.Password = "密碼"
End With
con.ConnectionString = sqlConnectionSB.ConnectionString
con.Open()
With cmd
.Connection = con
.CommandText = "SELECT * FROM AO_Log"
.CommandType = Data.CommandType.Text
End With
GridView1.DataSource = cmd.ExecuteReader
GridView1.DataBind()
con.Close()
cmd.Dispose()
End Sub
' 撈取OleDb的 Access 資料
Imports System.Data.OleDb
Sub getOleDbData()
Dim con As New OleDbConnection
Dim cmd As New OleDbCommand
Dim builder As New OleDbConnectionStringBuilder
With builder
.Provider = "Microsoft.Jet.OLEDB.4.0"
.DataSource = Server.MapPath("~/App_Data/Shopping_Cart_DB.mdb")
'若您的Access需要密碼時使用
' builder.Add("Jet OLEDB:Database Password", "123456")
End With
con.ConnectionString = builder.ConnectionString
con.Open()
With cmd
.Connection = con
.CommandText = "SELECT * FROM 個人資料"
.CommandType = Data.CommandType.Text
End With
GridView1.DataSource = cmd.ExecuteReader
GridView1.DataBind()
End Sub
沒有留言:
張貼留言