標籤:
在asp.net中串連sqlserver資料庫之前,首先得確保正常安裝了sqlserver2008,同時有資料庫。
在項目中添加一個類DB,用來專門負責執行對資料庫的增刪改查。在添加的過程中會彈出下面的一個提示
直接點是就可以了。
在這個類中,首先定義一個連線物件 private SqlConnection conn = null;然後定義下面三個函數
private void SetConnection()//初始化連線物件
{
if (conn == null)
{
//擷取設定檔中的資料庫連接串
string connecteString = ConfigurationManager.ConnectionStrings["sqlContent"].ToString();
conn = new SqlConnection(connecteString);
}
}
//執行查詢資料庫的sql
public DataSet GetResult(string sql)
{
SetConnection();
conn.Open();
DataSet ds = new DataSet();
try
{
SqlCommand command = new SqlCommand(sql, conn);
SqlDataAdapter ad = new SqlDataAdapter(command);
ad.Fill(ds);
}
catch
{ }
finally
{
conn.Close();
}
return ds;
}
//執行添加和修改,刪除的函數
public bool Exemend(string sql)
{
SetConnection();
conn.Open();
SqlCommand cmd = null;
SqlTransaction trans = conn.BeginTransaction(); //建立事務
try
{
cmd = new SqlCommand(sql,conn,trans); //建立命令對象
int num=cmd.ExecuteNonQuery();
if (num > 0)
return true;
else
return false;
}
catch (Exception e)
{
trans.Rollback();//交易回復
Console.WriteLine(e.Message.ToString());
return false;
}
finally
{ conn.Close(); }
}
然後再來配置一下資料庫連接字串,開啟設定檔web.config
其中.表示本機,如果是伺服器,那就是伺服器的IP了,MRS表示資料庫名稱。
到此,sqlserver的資料庫連接就做好了,就可以在業務代碼中通過調用GetResult和Exemend來實現對資料庫的增刪改查了。
C#中,與資料庫打交道的常用的5個類:DataSet資料集,相當於記憶體中的資料庫,SqlDataAdapter資料配接器,SqlConnection資料庫連接對象,SqlCommand資料庫命令對象,SqlDataReader 資料庫讀取器。
下面來看看控制項BulletedList通過綁定來顯示從資料庫中查詢的資料:
在前台代碼中,先預置幾個項,來看看最終顯示的效果。
後台對資料的綁定
顯示結果。可以看到,顯示的結果並沒有顯示預置的項目。
asp.net 串連sqlserver資料庫