一.用SqlConnection連接SQL Server
1..加入命名空間
using System.Data.SqlClIEnt;
2.連接數據庫
SqlConnection myConnection = new SqlConnection();
myConnection.ConnectionString = "user id=sa;passWord=sinofindb;initial catalog=test;data source=127.0.0.1;Connect Timeout=30";
myConnection.Open();
改進(更通用)的方法:
string MySQLConnection="user id=sa;passWord=sinofindb;Database =test;data source=127.0.0.1;Connect Timeout=30";
SqlConnection myConnection = new SqlConnection(MySQLConnection);
myConnection.Open();
二、用OleDbConnection連接
1.加入命名空間
using System.Data.OleDb;
2.連接SQL Server
string MySQLConnection="Provider=SQLOLEDB;Data Source=localhost;Initial Catalog=test;Integrated Security=SSPI;";
SqlConnection myConnection = new SqlConnection(MySQLConnection);
myConnection.Open();
3.連接Access(可通過建立.udl文件獲得字符串)
string MySQLConnection="Provider=Microsoft.Jet.OLEDB.4.0;Data Source=c:\db2000.mdb;
Persist Security Info=False;
4.連接Oracle(也可通過OracleConnection連接)
string MySQLConnection="Provider=MSDAORA;Data Source=db; user id=sa;passWord=sinofindb";
三.創建Command對象
1.SqlCommand 構造函數
①初始化 SqlCommand 類的新實例。public SqlCommand();
SqlCommand myCommand = new SqlCommand();
②初始化具有查詢文本的 SqlCommand 類的新實例。public SqlCommand(string);
String mySelectQuery = "SELECT * FROM mindata";
SqlCommand myCommand = new SqlCommand(mySelectQuery);
③初始化具有查詢文本和 SqlConnection 的SqlCommand類實例。
Public SqlCommand(string, SqlConnection);
String mySelectQuery = "SELECT * FROM mindata";
string myConnectString = "user id=sa;passWord=;database=test;server=MySQLServer";
SqlConnection myConnection = new SqlConnection(myConnectString);
SqlCommand myCommand = new SqlCommand(mySelectQuery,myConnection);
④初始化具有查詢文本、SqlConnection 和 Transaction 的 SqlCommand 類實例。
public SqlCommand(string, SqlConnection, SqlTransaction);
SqlTransaction myTrans = myConnection.BeginTransaction();
String mySelectQuery = "SELECT * FROM mindata";
string myConnectString = "user id=sa;passWord=;database=test;server=MySQLServer";
SqlConnection myConnection = new SqlConnection(myConnectString);
SqlCommand myCommand = new SqlCommand(mySelectQuery,myConnection, myTrans);