ADO.NET基础学习

(记录下方便自己复习)

概念

简单地理解为用来连接数据库的类。

工作流程

①Connection对象用来连接数据库。

两种连接方式:Windows身份验证 / sqlserver验证

 private void button1_Click(object sender, EventArgs e)
        {
                try
                {
                   
                    //string Str = "server=.;Initial catalog="db_PWMS";integrated security=SSPI";//windows身份验证
                    string Str = "server=.;database="db_PWMS";uid=sa;pwd=***";//Sqlserver验证
                    //声明Str存储连接数据库的字符串。
                    //server=.。 服务器名称=等于本地 。
                    //Initial catalog="db_PWMS"   数据库名=db_PWMS。
                    SqlConnection conn= new SqlConnection(Str);//声明对象
                    conn.Open();//连接上
                    if (conn.State==ConnectionState.Open)//State属性判断打开与否
                    {
                        richTextBox1.Text = "已经打开";
                    }
                }
                catch
                {
                    MessageBox.Show("连接失败");
                }

        }

②command对象用来操作数据库。(三个重要的方法:ExecuteNonQuery(),ExecuteReader(),ExecuteScalar())

⑴以update(改数据)为例,用到ExecuteNonQuery()方法

 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)

执行前数据库

 

执行后

 ⑵以各种姿势查数据ExecuteScalar()

此方法的聚合函数

  说明
AVG() 平均值
count() 有几条数据
max() 最大值
min() 最小值
sum()

以count()和max()为例

 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 (2) 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); }
        }

猜你喜欢

转载自www.cnblogs.com/zx3180/p/9112897.html