首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 數據庫知識 >  >> SQL Server 資料庫 >> 關於SqlServer

C# 使用 OLE DB 連接 SQL Server 2000 完整範例

     編輯:關於SqlServer

環境建置

  1. 安裝 SQL Server 2000(含 OLE DB Provider)。
  2. 企業管理員建立資料庫 tyjdb 與資料表 address(欄位:name、email、age、address)。
  3. VS.NET 伺服器總管新增資料連線,提供者選 Microsoft OLE DB Provider for SQL Server,測試成功後拖曳至 Web Form 自動產生連線字串。

連線字串範例

data source=WHOAMI;initial catalog=tyjdb;integrated security=SSPI;
persist security info=False;workstation id=WHOAMI;packet size=4096

資料顯示(DataGrid)

protected System.Data.SqlClient.SqlDataAdapter sqlDataAdapter1;
protected System.Data.SqlClient.SqlCommand sqlSelectCommand1;
protected System.Data.SqlClient.SqlConnection sqlConnection1;

// InitializeComponent 內
sqlSelectCommand1.CommandText = "SELECT name, email, age, address FROM address";
sqlSelectCommand1.Connection = sqlConnection1;
sqlDataAdapter1.SelectCommand = sqlSelectCommand1;

// Page_Init
sqlConnection1.Open();
DataSet ds = new DataSet();
sqlDataAdapter1.Fill(ds, "address");
DataGrid1.DataSource = ds.Tables["address"].DefaultView;
DataGrid1.DataBind();
sqlConnection1.Close();

新增資料

表單置放四個 TextBox 對應欄位,按鈕 Click 事件:

sqlInsertCommand1.Parameters["@name"].Value = TextBox1.Text;
sqlInsertCommand1.Parameters["@email"].Value = TextBox2.Text;
sqlInsertCommand1.Parameters["@age"].Value = TextBox3.Text;
sqlInsertCommand1.Parameters["@address"].Value = TextBox4.Text;
sqlInsertCommand1.Connection.Open();
sqlInsertCommand1.ExecuteNonQuery();
sqlInsertCommand1.Connection.Close();

// 重新繫結 DataGrid
sqlConnection1.Open();
DataSet ds = new DataSet();
sqlDataAdapter1.Fill(ds, "address");
DataGrid1.DataSource = ds.Tables["address"].DefaultView;
DataGrid1.DataBind();

刪除資料

SqlCommand cmd = new SqlCommand();
cmd.CommandText = "DELETE FROM address WHERE name=@name";
cmd.Parameters.AddWithValue("@name", TextBox5.Text);
cmd.Connection = sqlConnection1;
cmd.Connection.Open();
cmd.ExecuteNonQuery();
cmd.Connection.Close();

結語

善用 VS.NET 設計工具拖曳元件、自動產生參數化命令,能大幅提升開發效率與程式碼品質。本範例在中文 Windows 2000 Server + SQL Server 2000 + VS.NET Beta 2 環境編譯執行正常。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved