asp.net 串連sqlserver資料庫

來源:互聯網
上載者:User

標籤:

在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資料庫

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.