國際原油價格來到126?!那接下來呢? BindingSource 和 BindingNavigator
五月 20

建立資料庫連接字串的方法

程式.瀏覽:[ 3,891user+2,976機器人 ]給個回應

一、使用 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"

標籤: ,



文章發表日期:2008-05-20
本篇文章引用網址:

其他隨機文章:
  • 正義女神的天坪,只辦綠不辦藍?
  • 使用兩個簡易工具來偵測網路情況
  • XML速記
  • 物件導向無痛入門(1)
  • 四年來最大跌幅!台股單日重挫528點,這只是剛開始而已...


  • 2 個回應在 “建立資料庫連接字串的方法”

    1. 聽.風 說道:

      感謝大大的教學
      不過關於
      da.Fill(ds, "pro")
      DataGridView1.DataSource = ds.Tables("pro")
      這兩行有點不能理解
      這兩行意思大概是說把取得的資料顯示到控制項
      但是如果我想把取得的資料存入一個變數中
      並且是在主控台應用程式的情況下撰寫程式
      以PHP來講就是想要做到:
      $x=mysql_query('select * from `test` limit 1;);
      echo mysql_fetch_array($x);
      的功能

      [回應]

      blue955 Reply:

      類似,這是C#的程式碼,PHP應該沒有這種容器的概念,你的這行PHP應該說是把資料丟到變數裡,然後印出來...

      [回應]


    寫下回應