一、使用 ConnectionStringBuilder
1.連接 Access

VB.NET:
  1. Dim builder As New OleDbConnectionStringBuilder
  2. builder.Provider = "Microsoft.Jet.OLEDB.4.0"
  3. builder.DataSource = "|DataDirectory|\test.mdb"
  4. builder.Add("Jet OLEDB:Database Password", "123456")
  5. Dim str As String = builder.ConnectionString
  6. Return str


2.連接 SQLServer

VB.NET:
  1. Dim builder As New SqlConnectionStringBuilder
  2. builder.DataSource = "(local)\SQLEXPRESS"
  3. builder.InitialCatalog = "北風貿易"
  4. builder.IntegratedSecurity = True
  5. Dim str As String = builder.ConnectionString
  6. Return str

 


 

3.連接 MySql (必須安裝 MySql.Data 外掛) 請參考...

VB.NET:
  1. Imports MySql.Data
  2. Imports MySql.Data.MySqlClient
  3.  
  4. Public Class Form1
  5.     Private Sub Form1_Load(ByVal sender As System.Object, _
  6.     ByVal e As System.EventArgs) Handles MyBase.Load
  7.  
  8.         Dim builder As New MySqlConnectionStringBuilder
  9.         builder.Server = "localhost"
  10.         builder.UserID = "root"
  11.         builder.Password = "123456"
  12.         builder.Database = "test"
  13.         Dim str As String = builder.ConnectionString
  14.  
  15.         Dim conn As New MySqlConnection(str)
  16.         Dim commCMD As String = "select * from product"
  17.         Dim da As New MySqlDataAdapter(commCMD, conn)
  18.         Dim ds As New DataSet
  19.         conn.Open()
  20.         da.Fill(ds, "pro")
  21.         DataGridView1.DataSource = ds.Tables("pro")
  22.         conn.Close()
  23.     End Sub
  24. End Class

 

二、使用自行撰寫連線字串,此方法容易因為人為疏失而產生錯誤
1.連接 SQLServer

VB.NET:
  1. Me.SqlConnection1.ConnectionString = _
  2. "Data Source=(local)\SQLEXPRESS; _
  3. Initial Catalog=北風貿易; _
  4. Integrated Security=True"

阿倫 發表在 痞客邦 PIXNET 留言(0) 人氣()