ASP.NET總結ADO.NET操作數據庫五大對象


1、Connection對象主要提供與數據庫的連接功能

配置web.config文件

<appSettings>
<add key="ConnectionString" value="Server=10.136.*.*;database=MTL;uid=sa;pwd=sa;"/>
</appSettings>

創建獲取配置節的連接字符串

public SqlConnection GetSqlConnection()

{
   string str = ConfigurationManager.AppSettings["ConnectionString"].ToString();
   SqlConnection sqlconn = new SqlConnection(str);
   return sqlconn;

}

        string str = "Server=(local); userid=sa;pwd=123456;database=SQLName";
       //創建SqlConnection對象,並設置連接數據庫字符串
        SqlConnection sql = new SqlConnection(str);
        sql.Open();//打開數據庫連接
        //數據庫相關操作.....
        sql.Close();//關閉數據庫連接(不關閉將會消耗內存資源)
示例代碼

 

2、Command對象主要對數據源進行增、刪、查、改等操作;下面舉幾個例子:

     查詢操作

 if (SqlCommandText.Text != "")
        {
            try
            {
                SqlConnection MyConn = GetSqlConnection();
                MyConn.Open();
                string StrString = "select * from Table1 where State=@State";
                SqlCommand Sqlcmd = new SqlCommand(StrString, MyConn);
                Sqlcmd.Parameters.Add("@State", SqlDbType.NVarChar, 2).Value = this.SqlCommandText.Text.Trim();

                SqlDataAdapter MyDataAdpater = new SqlDataAdapter(Sqlcmd);
                DataSet ds = new DataSet();
                MyDataAdpater.Fill(ds);
                if (ds.Tables[0].Rows.Count > 0)
                {
                    Response.Write("存在此信息!");
                }
                else
                {
                    Response.Write("不存在此信息!");
                }
            }
            catch (Exception ex)
            {

                Response.Write(ex.Message);
            }
        }
示例代碼

     添加操作

        if (this.SqlCommandText.Text.Trim() != "")
        {
            try
            {
                SqlConnection SqlConn = GetSqlConnection();
                SqlConn.Open();
                string Str = "insert into Table1(State) values('" + this.SqlCommandText.Text.Trim() + "')";
                SqlCommand Sqlcomm = new SqlCommand(Str, SqlConn);
                Sqlcomm.ExecuteNonQuery();
                SqlConn.Close();
                Response.Write("添加成功!");
            }
            catch (Exception ex)
            {
                Response.Write(ex.Message);
            }
        }
示例代碼

     調用存儲過程

        //存儲過程代碼,向db_table里面插入數據;
        use db_table
        go
        Create proc ProcClass
        (@Name varchar(50))
        as
        insert into Table1(Name) values(@Name)
        go

        //存儲過程可以使管理數據庫和顯示數據庫信息等錯做變得非誠容易,它是SQL語句和可選控制流語句的預編譯集合,
        //存儲在數據庫內,在程序中可以通過SqlCommand對象來調用,其執行速度比SQL語句塊
        SqlConnection Sqlconn = GetSqlConnection();
        Sqlconn.Open();
        SqlCommand cmd = new SqlCommand("ProcClass", Sqlconn);
        cmd.CommandType = CommandType.StoredProcedure;
        cmd.Parameters.Add("@Name", SqlDbType.VarChar, 50).Value = this.SqlCommandText.Text.Trim();
        cmd.ExecuteNonQuery();
        cmd.Dispose();
        Sqlconn.Close();
示例代碼

    實現事務的處理

        //事務:事務是由一組相關任務組成的單元,該單元的任務要么全部成功,要么全部失敗;事務最終執行的結果是兩種狀態,即提交和終止;
        SqlConnection Sqlconn = GetSqlConnection();
        Sqlconn.Open();
        string str = "insert into EquipmentInfo(State) values('" + this.SqlCommandText.Text.Trim() + "')";
        SqlTransaction SqlTran = Sqlconn.BeginTransaction();
        SqlCommand cmd = new SqlCommand(str, Sqlconn);
        cmd.Transaction = SqlTran;
        try
        {
            cmd.ExecuteNonQuery();
            SqlTran.Commit();
            Sqlconn.Close();
            Response.Write("添加成功!");
        }
        catch (Exception ex)
        {
            Response.Write("添加失敗!");
            throw;
        }
示例代碼

 

3、DataAdapter數據適配器和DataSet數據集

SqlDataAdapter對象是DataSet對象和數據源之間聯系的橋梁;
主要從數據源中檢索數據,填充DataSet對象中的表或者把用戶對DataSet對象做出的修改寫入數據源;

        DataSet ds = new DataSet();
        string str = "select * from Table1";
        SqlConnection conn = GetSqlConnection();
        conn.Open();
        SqlDataAdapter sqlda = new SqlDataAdapter(str, conn);
        sqlda.Fill(ds);
示例代碼

 

4、DataReader對象讀取器 

讀取器以基於連接的,快速的、未緩沖的及只向前移動的方式來讀取數據,
一次讀取一條記錄,然后遍歷整個結果集;

        SqlConnection Sqlconn = GetSqlConnection();
        string str = "select * from Table1";
        SqlCommand cmd = new SqlCommand(str, Sqlconn);
        cmd.CommandType = CommandType.Text;
        try
        {
            Sqlconn.Open();
            //執行sql語句,並返回DataReader對象
            SqlDataReader Reader = cmd.ExecuteReader();
            this.SqlCommandText.Text = "序號,新聞內容 ";
            while (Reader.Read())
            {
                this.SqlCommandText.Text += Reader["NewsID"] + "," + Reader["NewsContent"];
            }
            Reader.Close();
        }
        catch (Exception ex)
        {

            Response.Write(ex.ToString());
        }
        finally 
        {
            Sqlconn.Close();
        }
示例代碼

----------------個人學習過程中的一些總結,寫的有不對的地方還請多多指教---------------------


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM