ASP.NET總結ADO.NET操作資料庫五大對象

來源:互聯網
上載者:User

標籤:

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 [email protected]";                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();        }
範例程式碼

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

ASP.NET總結ADO.NET操作資料庫五大對象

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.