ADO.NET基礎學習 二(Command對象)

②command對象用來操做數據庫。(三個重要的方法:ExecuteNonQuery(),ExecuteReader(),ExecuteScalar())數據庫

 

⑴以update(改數據)爲例,用到ExecuteNonQuery()方法(執行SQL語句,返回受影響行)函數

 

private void button2_Click(object sender, EventArgs e)
        {
                SqlConnection conn =new SqlConnection("server=.;Initial catalog=db_PWMS;integrated security=SSPI");
                conn.Open();//老規矩,先鏈接
            try
            {
                SqlCommand cmd = new SqlCommand();//實例操做項cmd
                cmd.Connection = conn;//操做conn這個數據庫
                cmd.CommandText = "update Table_1 set Prices =3333 where Origin ='國產'";//操做這樣一句SQL語句
                cmd.CommandType = CommandType.Text;//書上這麼寫的,不知道幹嗎的,之後知道了再說。去掉這句話也沒事。
                cmd.ExecuteNonQuery();//command對象重要的三個方法之一,執行增刪改
                int i = Convert.ToInt32(cmd.ExecuteNonQuery());
                label2.Text = i + "條數據發生改動";
            }
            catch (Exception ex){ MessageBox.Show(ex.Message); }
        }

 

點擊事件(button2)spa

執行前數據庫3d

 

執行後code

 ⑵以各類姿式查數據ExecuteScalar()方法(執行SQL語句,返回結果集中第一行第一列),但此方法一般與聚合函數一塊兒使用server

此方法的聚合函數對象

  說明
AVG() 平均值
count(列名)/count(*) 此列值的計數(不包括空值)/此表全部行的計數(包括空值)
max() 最大值
min() 最小值
sum()

 

 

 

 

 

 

以count()和max()爲例blog

private void button3_Click(object sender, EventArgs e)
        {
            conn = new SqlConnection("server=.;Initial catalog=db_PWMS;integrated security=SSPI");
            conn.Open();
            try
            {
                string s1 = "select count (*) from Table_1";//表數量count()
                string s2 = "select max (Prices) from Table_1";//Prices最大值max()

                SqlCommand cmd = new SqlCommand(s1,conn);
                SqlCommand cmd1 = new SqlCommand(s2,conn);
                int i = Convert.ToInt32(cmd.ExecuteScalar());//對象轉int類型
                int j = Convert.ToInt32(cmd1.ExecuteScalar());

                label2.Text = i+"條數據";
                label1.Text = "最貴的" + j;
            }
            catch (Exception ex){ MessageBox.Show(ex.Message); }
        }

 

ExecuteReader()方法(執行SQL語句,生成一個SqlDataReader對象的實例,返回 一個SqlDataReader對象)事件

private void button5_Click(object sender, EventArgs e)
        {
            SqlConnection conn = new SqlConnection("server=.;Initial catalog=db_PWMS;integrated security=SSPI");
            conn.Open();//鏈接並打開
            SqlCommand cmd = new SqlCommand("select * from Table_1",conn);//操做
            SqlDataReader sdr = cmd.ExecuteReader();//ExecuteReader方法實例化個SqlDataReader對象
            while (sdr.Read())//SqlDataReader的Read()方法 循環讀取數據
            {
                label3.Text += sdr[1].ToString();//讀取第一列
                listView1.Items.Add(sdr[2].ToString());//讀取第二列
            }
        }

相關文章
相關標籤/搜索