C#的各種連接數據庫

C#的各種連接數據庫2007年11月01日 星期四 11:461.C#連接連接Access 程序代碼: ------------------------------------------------------------------------------- using System.Data; using System.Data.OleDb; ...... string strConnection="Provider=Microsoft.Jet.OleDb.4.0;"; strConnection+=@"Data Source=C:/BegASPNET/Northwind.mdb"; OleDbConnection objConnection=new OleDbConnection(strConnection); ...... objConnection.Open(); objConnection.Close(); ...... -------------------------------------------------------------------------------- 解釋: 連接Access數據庫需要導入額外的命名空間,所以有了最前面的兩條using命令,這是必不可少的! strConnection這個變量裏存放的是連接數據庫所需要的連接字符串,他指定了要使用的數據提供者和要使用的數據源. "Provider=Microsoft.Jet.OleDb.4.0;"是指數據提供者,這裏使用的是Microsoft Jet引擎,也就是Access中的數據引擎,asp.net就是靠這個和Access的數據庫連接的. "Data Source=C:/BegASPNET/Northwind.mdb"是指明數據源的位置,他的標準形式是"Data Source=MyDrive:MyPath/MyFile.MDB". PS: 1."+="後面的"@"符號是防止將後面字符串中的"/"解析爲轉義字符. 2.如果要連接的數據庫文件和當前文件在同一個目錄下,還可以使用如下的方法連接: strConnection+="Data Source="; strConnection+=MapPath("Northwind.mdb"); 這樣就可以省得你寫一大堆東西了! 3.要注意連接字符串中的參數之間要用分號來分隔. "OleDbConnection objConnection=new OleDbConnection(strConnection);"這一句是利用定義好的連接字符串來建立了一個鏈接對象,以後對數據庫的操作我們都要和這個對象打交道. "objConnection.Open();"這用來打開連接.至此,與Access數據庫的連接完成. -------------------------------------------------------------------------------- 2.C#連接SQL Server 程序代碼: -------------------------------------------------------------------------------- using System.Data; using System.Data.SqlClient; ... string strConnection="user id=sa;password=;"; strConnection+="initial catalog=Northwind;Server=YourSQLServer;"; strConnection+="Connect Timeout=30"; SqlConnection objConnection=new SqlConnection(strConnection); ... objConnection.Open(); objConnection.Close(); ... -------------------------------------------------------------------------------- 解釋: 連接SQL Server數據庫的機制與連接Access的機制沒有什麼太大的區別,只是改變了Connection對象和連接字符串中的不同參數. 首先,連接SQL Server使用的命名空間不是"System.Data.OleDb",而是"System.Data.SqlClient". 其次就是他的連接字符串了,我們一個一個參數來介紹(注意:參數間用分號分隔): "user id=sa":連接數據庫的驗證用戶名爲sa.他還有一個別名"uid",所以這句我們還可以寫成"uid=sa". "password=":連接數據庫的驗證密碼爲空.他的別名爲"pwd",所以我們可以寫爲"pwd=". 這裏注意,你的SQL Server必須已經設置了需要用戶名和密碼來登錄,否則不能用這樣的方式來登錄.如果你的SQL Server設置爲Windows登錄,那麼在這裏就不需要使用"user id"和"password"這樣的方式來登錄,而需要使用"Trusted_Connection=SSPI"來進行登錄. "initial catalog=Northwind":使用的數據源爲"Northwind"這個數據庫.他的別名爲"Database",本句可以寫成"Database=Northwind". "Server=YourSQLServer":使用名爲"YourSQLServer"的服務器.他的別名爲"Data Source","Address","Addr".如果使用的是本地數據庫且定義了實例名,則可以寫爲"Server=(local)/實例名";如果 是遠程服務器,則將"(local)"替換爲遠程服務器的名稱或IP地址. "Connect Timeout=30":連接超時時間爲30秒. 在這裏,建立連接對象用的構造函數爲:SqlConnection. -------------------------------------------------------------------------------- 3.C#連接Oracle 程序代碼: -------------------------------------------------------------------------------- using System.Data.OracleClient; using System.Data; //在窗體上添加一個按鈕,叫Button1,雙擊Button1,輸入以下代碼 private void Button1_Click(object sender, System.EventArgs e) { string ConnectionString="Data Source=sky;user=system;password=manager;";//寫連接串 OracleConnection conn=new OracleConnection(ConnectionString);//創建一個新連接 try { conn.Open(); OracleCommand cmd=conn.CreateCommand(); cmd.CommandText="select * from MyTable";//在這兒寫sql語句 OracleDataReader odr=cmd.ExecuteReader();//創建一個OracleDateReader對象 while(odr.Read())//讀取數據,如果odr.Read()返回爲false的話,就說明到記錄集的尾部了 { Response.Write(odr.GetOracleString(1).ToString());//輸出字段1,這個數是字段索引,具體怎麼使用字段名還有待研究 } odr.Close(); } catch(Exception ee) { Response.Write(ee.Message); //如果有錯誤,輸出錯誤信息 } finally { conn.Close(); //關閉連接 } } -------------------------------------------------------------------------------- 4.C#連接MySQL 程序代碼: -------------------------------------------------------------------------------- using MySQLDriverCS; // 建立數據庫連接 MySQLConnection DBConn; DBConn = new MySQLConnection(new MySQLConnectionString("localhost","mysql","root","",3306).AsString); DBConn.Open(); // 執行查詢語句 MySQLCommand DBComm; DBComm = new MySQLCommand("select Host,User from user",DBConn); // 讀取數據 MySQLDataReader DBReader = DBComm.ExecuteReaderEx(); // 顯示數據 try { while (DBReader.Read()) { Console.WriteLine("Host = {0} and User = {1}", DBReader.GetString(0),DBReader.GetString(1)); } } finally { DBReader.Close(); DBConn.Close(); } //關閉數據庫連接 DBConn.Close(); -------------------------------------------------------------------------------- 5.C#連接IBM DB2 程序代碼: -------------------------------------------------------------------------------- OleDbConnection1.Open(); //打開數據庫連接 OleDbDataAdapter1.Fill(dataSet1,"Address"); //將得來的數據填入dataSet DataGrid1.DataBind(); //綁定數據 OleDbConnection1.Close(); //關閉連接 //增加數據庫數據 在Web Form上新增對應字段數量個數的TextBox,及一個button,爲該按鍵增加Click響應事件代碼如下: this.OleDbInsertCommand1.CommandText = "INSERTsintosADDRESS(NAME, EMAIL, AGE, ADDRESS) valueS (''"+TextBox1.Text+"'',''"+TextBox2.Text+"'',''"+TextBox3.Text+"'',''"+TextBox4.Text+"'')"; OleDbInsertCommand1.Connection.Open(); //打開連接 OleDbInsertCommand1.ExecuteNonQuery(); //執行該SQL語句 OleDbInsertCommand1.Connection.Close(); //關閉連接 -------------------------------------------------------------------------------- 6.C#連接SyBase 程序代碼: (OleDb) -------------------------------------------------------------------------------- Provider=Sybase.ASEOLEDBProvider.2;Initial Catalog=數據庫名;User ID=用戶名;Data Source=數據源;Extended Properties="";Server Name=ip地址;Network Protocol=Winsock;Server Port Address=5000; Visual C 連接數據庫 - 連接SQL Server 2000 使用DAO 看下面的代碼: CDaoDatabase db; CString conn; conn="ODBC;Driver= SQLServer};Server=192.168.0.4;Database=mydb;uid=sa;pwd="; db.Open(NULL,FALSE,FALSE,conn); CString s=db.GetConnect(); CDaoRecordset rs(&db); rs.Open(AFX_DAO_USE_DEFAULT_TYPE,"select * from tb_code"); TRACE("%drn",rs.GetRecordCount()); rs.Close(); db.Close(); 其中Server=192.168.0.4是sql server服務器的ip地址,也可以用主機名錶示;Database=mydb表示使用mydb數據庫;uid和pwd分別表示訪問數據庫的用戶名和密碼。 注意:上面的代碼的運行還要用#include "afxdao.h" 把afxdao.h包含進來。當然最好還是加入些必要的出錯處理代碼,這裏就不在詳述了。 二 連接 Microsoft Access數據庫 看下面實例的代碼,這也是我用的比較多的一種方法,access文件只要放在和應用程序相同的文件夾中就能保證代碼可以正確執行。 CString sPath,message; GetModuleFileName(NULL,sPath.GetBufferSetLength (MAX_PATH+1),MAX_PATH); sPath.ReleaseBuffer(); int nPos; nPos=sPath.ReverseFind(''); sPath=sPath.Left(nPos); CString runpath=sPath+"clzmf.mdb"; //這裏的clzmf.mdb就是要打開的數據庫名 runpath.Replace('','/'); m_pDatabase=new CDaoDatabase; try { m_pDatabase->Open(runpath); } catch(CDaoException *e) { message=_T("Could't open database-- Exception:"); message+=e->m_pErrorInfo->m_strDescription; AfxMessageBox(message); } CString sqlstr="select * from user_info where user_id='myid'; CDaoRecordset rs(m_pDatabase); try { rs.Open(AFX_DAO_USE_DEFAULT_TYPE,sqlstr); } catch(CDaoException *e) { message=_T("Could't open Recordset-- Exception:"); message+=e->m_pErrorInfo->m_strDescription; AfxMessageBox(message); } 這裏加入了異常處理的代碼,其他注意選項可以參照Sql Server 2000的注意選項。 #連接SQL數據庫並且在表中進行對數據操作2007-11-30 16:07using System; using System.Collections.Generic; using System.Text; using Model; using System.Data; using System.Data.SqlClient; //在表中修改 private void btnOK_Click(object sender, EventArgs e) { try { DialogResult result = MessageBox.Show("你確定?", "系統提示", MessageBoxButtons.YesNo, MessageBoxIcon.Question); if (result == DialogResult.Yes) { //string strConn = "server=.;uid=sa;pwd=;database=wareDB"; string strConn = "server=.;uid=sa;pwd=;database=ShopManegerDB"; SqlConnection conn = new SqlConnection(strConn); SqlCommand cmd = new SqlCommand(); cmd.Connection = conn; cmd.CommandText = "select * from Shop"; SqlDataAdapter da = new SqlDataAdapter(); da.SelectCommand = cmd; //獲取選擇命令 //創建自動生成Sql對象 SqlCommandBuilder builder = new SqlCommandBuilder(da); //保存修改 da.Update(ds.Tables[0]); //提交更新 MessageBox.Show("修改成功"); this.Isindsplay(); } } catch (Exception ex) { MessageBox.Show(ex.Message); } } //在表中操作刪除 private void 刪除ToolStripMenuItem_Click(object sender, EventArgs e) { //保證選中 if (dgvData.CurrentCell.RowIndex != -1) { DialogResult result = MessageBox.Show("你確定?", "系統提示", MessageBoxButtons.YesNo, MessageBoxIcon.Question); if (result == DialogResult.Yes) { //刪除 ds.Tables[0].Rows[dgvData.CurrentCell.RowIndex].Delete(); //刪除該選中行 } } } 刪除成功後,在次按保存按鈕.

http://hi.baidu.com/xiapengkun/blog/item/b6c8e32253f78bf0d6cae2f3.html(來源)

發佈了11 篇原創文章 · 獲贊 2 · 訪問量 5萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章