欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

當(dāng)年學(xué)習(xí)ADO.NET的筆記

 更新時(shí)間:2012年03月06日 23:15:14   作者:  
那些年學(xué)習(xí)了ASP.NET后又開始學(xué)習(xí)ASP.NET的新知識(shí),ADO.NET用于訪問數(shù)據(jù)庫,一般可以分為連接模式和非連接模式
那些年我還在學(xué)ADO.NET
那些年學(xué)習(xí)了ASP.NET后又開始學(xué)習(xí)ASP.NET的新知識(shí),ADO.NET用于訪問數(shù)據(jù)庫,一般可以分為連接模式和非連接模式。連接模式指的是在訪問數(shù)據(jù)時(shí),一直與數(shù)據(jù)庫保持連接,訪問完數(shù)據(jù)后才與數(shù)據(jù)庫斷開連接,主要采用的ADO.NET對象是Connection、Command、DataReader等;連接模式指的是通過數(shù)據(jù)集的方式對數(shù)據(jù)庫進(jìn)行操作,將數(shù)據(jù)讀到內(nèi)存中,從而完成數(shù)據(jù)的操作,數(shù)據(jù)集會(huì)自動(dòng)更新到數(shù)據(jù)庫,主要采用ADO.NET對象是DataAdapter、DataSet等。下面的我們就來看一下代碼吧。
本示例代碼采用工廠模式的方式,這樣就可以達(dá)到只改變少量的代碼完成數(shù)據(jù)庫之間的切換,工廠模式是要采用的對象有以下幾個(gè):DbProviderFactory、DbConnection、DbTransaction
、DbCommand、DbDataReader、DbDataAdapter、DbCommandBuilder等。

1、 共同的連接串

復(fù)制代碼 代碼如下:

string ProviderName = "System.Data.SqlClient";
string ConnStr = "Data Source=.;Initial Catalog=Northind;Integrated Security=True";
string sqlStr = "select * from dbo.Categories";


2、 非連接模式代碼如下:

復(fù)制代碼 代碼如下:

public void getSqlConnection()
{
//得到一個(gè)數(shù)據(jù)提供者,根據(jù)其傳入的數(shù)據(jù)提供者對象
DbProviderFactory dbf = DbProviderFactories.GetFactory(ProviderName);
//創(chuàng)建連接
DbConnection conn = dbf.CreateConnection();
//連接字符串
conn.ConnectionString = ConnStr;
conn.Open();
DbTransaction ts = conn.BeginTransaction();
DbCommand dbcmd = null;
try
{
dbcmd = dbf.CreateCommand();
dbcmd.CommandText = sqlStr;
dbcmd.Connection = conn;
dbcmd.Transaction = ts;
DbDataReader dr = dbcmd.ExecuteReader();
while (dr.Read())
{
Console.WriteLine(dr[1].ToString());
}
dr.Close();
ts.Commit();
}
catch (Exception e)
{
ts.Rollback();
}
finally
{
conn.Close();
if (dbcmd != null)
{
dbcmd.Dispose();
}
}
}

效果:

3、 連接模式代碼:
復(fù)制代碼 代碼如下:

public void getDataSetConnection()
{
//得到一個(gè)數(shù)據(jù)提供者,根據(jù)其傳入的數(shù)據(jù)提供者對象
DbProviderFactory dbf = DbProviderFactories.GetFactory(ProviderName);
//創(chuàng)建連接
DbConnection conn = dbf.CreateConnection();
//連接字符串
conn.ConnectionString = ConnStr;
//創(chuàng)建DataAdapter對象
DbDataAdapter da = dbf.CreateDataAdapter();
//創(chuàng)建自動(dòng)生成sql語句對象
DbCommandBuilder dbCmdb = dbf.CreateCommandBuilder();
using (DbCommand dbcmd = dbf.CreateCommand())
{
dbcmd.CommandText = sqlStr;
dbcmd.Connection = conn;
//DbDataAdapter指定命令
da.SelectCommand = dbcmd;
//DbCommandBuilder指定dataAdpter
dbCmdb.DataAdapter = da;
DataSet ds = new DataSet();
da.Fill(ds);
// ds.Tables[0].Rows[0].Delete();
da.Update(ds);
DataTable dt = ds.Tables[0];
DataRow dr;
for (int i = 0; i < dt.Rows.Count; i++)
{
dr = dt.Rows[i];
Console.WriteLine(dr[1] + " " + dr[2]);
}
}
}

效果:

以上是一個(gè)簡單的例子,在正常情況下,就不會(huì)把連接串寫成字符串,應(yīng)放在config文件中,同樣SQL語句也會(huì)改為存儲(chǔ)過程,這樣改起來比較方便。

總結(jié)

那些年學(xué)習(xí)ADO.NET,基本了解了怎樣去訪問數(shù)據(jù)庫,對其進(jìn)行操作,現(xiàn)在.NET又有了一些新的方法,比如說使用Linq、DbContext等;此文以回憶那些年學(xué)習(xí)的日子。

相關(guān)文章

最新評(píng)論