數據庫學習任務三:執行數據庫操作命令對象SqlCommand


       數據庫應用程序的開發流程一般主要分為以下幾個步驟:

  1. 創建數據庫
  2. 使用Connection對象連接數據庫
  3. 使用Command對象對數據源執行SQL命令並返回數據
  4. 使用DataReader和DataSet對象讀取和處理數據源的數據

     

      使用Connection對象成功創建數據庫連接后,接下來就可以使用Command對象對數據源執行查詢、添加、刪除和修改等各種SQL命令了。

      SqlCommand對象用來對SQL Server數據庫執行操作命令。

 

 

1.ExecuteNonQuery方法,執行更新操作,如與 insert、delete 和 update 語句有關的操作

SqlConnection con = new SqlConnection();
con.ConnectionString ="連接字符串";
SqlCommand com = new SqlCommand();
com.Connection = con;
com.CommandText = "數據更新命令";
con.Open();
com.ExecuteNonQuery();  //執行Command命令
con.Close();

 

2.ExecuteReader方法,通常與查詢命令 select 一起使用,並返回一個數據讀取器對象 SqlDataReader 類的一個實例。

SqlConnection con = new SqlConnection();
con.ConnectionString = "連接字符串";
SqlCommand com = new SqlCommand();
com.Connection = con;
com.CommandText = "查詢語句";
con.Open();
SqlDataReader sdr = com.ExecuteReader();
while(sdr.Read()){
   Response.Write(sdr[0]);  //輸出第一個字段的內容
}
con.Close();

 

 

3.ExecuteScalar方法,如果只想檢索數據庫信息中的一個值,而不需要返回表或數據流形式的數據,即可使用此方法。例如只需要返回count(*)、avg(價格)、sum(數量)等函數的結果就可以使用此方法。

SqlConnection con = new SqlConnection();
con.ConnectionString = "連接字符串";
SqlCommand com = new SqlCommand();
com.Connection = con;
com.CommandText = "select avg(價格) from 你的表";
con.Open();
Response.Write(com.ExecuteScalar());  //輸出第一個字段的內容
con.Close();

 

 

【例】使用SqlComman對象增加數據庫數據,將注冊信息插入數據庫中

 protected void btnRegister_Click(object sender, EventArgs e)
    {
        SqlConnection con = new SqlConnection();
        con.ConnectionString = @"Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Users\ASUS\Desktop\案例\EBookShop\App_Data\ShopBookDB.mdf;Integrated Security=True;User Instance=True";
        SqlCommand com = new SqlCommand();
        com.Connection = con;
        com.CommandText = string.Format("insert into users(user_name,password,sex,age,email,createDate) values('{0}','{1}','{2}','{3}','{4}','{5}')",txtName.Text.Trim(),txtPwd.Text.Trim(),rbFemale.Checked?"":"",txtAge.Text.Trim(),txtEmail.Text.Trim(),DateTime.Now.ToShortDateString());
        con.Open();
        com.ExecuteNonQuery();
        try {
            Response.Write("<script>alert('注冊成功')</script>");
            con.Close();
        }
        catch(Exception){
            Response.Write("<script>alert('數據庫無法連接')</script>");
            con.Close();
        }
        
    }

 


免責聲明!

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



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