C#-从入门到精通-第13章 数据访问技术

【简单的sql语句】
1.查询数据

//查询表tb_test中新旧程度为二手的数据
select * from tb_test where 新旧程度=' 二手 '

2.添加数据

insert into tb_test(商品名称,商品价格)values(' 洗衣机 ',' 890 ')

3.更新数据

//将表tb_test中商品名称为洗衣机的商品价格更新为1500
update tb_test set 商品价格=1500 where 商品名称=' 洗衣机 '

4.删除数据

//删除表db_test中商品名称为洗衣机,商品产地为进口的商品信息
delete from tb_test where 商品名称=' 洗衣机 ' and 商品产地=' 进口 '

【连接数据库:Connection对象】
1.连接数据库
SQL Server必须使用System.Data.SqlClient命名空间下的SqlConnection类。
通过Open方法打开数据库。通过State属性判断数据库的连接状态。
try…catch…finally语句

try{
可能出现异常的代码块
}
catch(异常类型  参数名){
用来捕捉异常,发生异常时就执行这块语句
}
finally{
始终会执行的代码块,不管有没有异常
}
private void button1_Click(object sender, EventArgs e)
        {
            if(textBox1.Text=="")
            {
                MessageBox.Show("请输入数据库名称");
            }
            else
            {
                try
                {
                    //声明连接字符串
                    string Constr = "server=LAPTOP-BVIBFPFE;database=" + textBox1.Text.Trim() + ";uid=sa;pwd=144159";
                    //创建SqlConnection对象,加载连接字符串
                    SqlConnection conn = new SqlConnection(Constr);
                    conn.Open();//打开连接
                    if(conn.State==ConnectionState.Open)
                    {
                        label2.Text = "数据库【" + textBox1.Text.Trim() + "】已成功连接";
                    }
                }
                catch
                {
                    MessageBox.Show("连接失败");
                }
            }

在这里插入图片描述
【关闭连接】
用Closs方法或者Dispose方法。
Closs方法关闭连接后,可以再次使用过Open方法打开连接。
Dispose方法关闭连接后,不能使用Open方法再次打开连接,必须重新初始化连接后才能再次打开连接。

SqlConnection conn;
        private void button1_Click(object sender, EventArgs e)
        {
            if (textBox1.Text == "")
            {
                MessageBox.Show("请输入数据库名称");
            }
            else
            {
                try
                {
                    string str = "server=MRC-8CF94303A82\\MRNET;database=" + textBox1.Text.Trim() + ";uid=sa;pwd=111";
                    conn = new SqlConnection(str);
                    conn.Open();
                    if (conn.State == ConnectionState.Open)
                    {
                        MessageBox.Show("连接成功");
                    }
                }
                catch(Exception ex)
                {
                    MessageBox.Show(ex.Message);
                    textBox1.Text = "";
                }
            }
        }
        private void button2_Click(object sender, EventArgs e)
        { 
            try
            {
                string str="";
                conn.Close();
                if (conn.State == ConnectionState.Closed)
                {
                    str="数据库已经成功关闭\n";
                }
                conn.Open();
                if (conn.State == ConnectionState.Open)
                {
                    str += "数据库已经成功打开\n";
                }
                richTextBox1.Text = str;
            }
            catch (Exception ex)
            {
                richTextBox1.Text = ex.Message;
            }
        }
        private void button3_Click(object sender, EventArgs e)
        {
            try
            {
                conn.Dispose();
                conn.Open();
            }
            catch (Exception ex)
            {
                richTextBox1.Text = ex.Message;
            }
        }

在这里插入图片描述
【执行SQL语句:Command对象】
1.设置数据源类型
Command对象共有三个重要属性。
Connection属性设置Command对象使用的SqlConnection。
CommandText属性设置SQL语句或者存储过程。
CommandType属性设置指定CommandText的类型。
CommandType有3个枚举成员:
StoredProcedure:存储过程的名称;
TableDirect:表的名称;
Text:SQL文本命令。
补充:Command对象的ExecuteScalar方法可以获取指定表中的数据数量。

SqlConnection conn;//声明成员变量,可以在方法中直接调用
        private void Form1_Load(object sender, EventArgs e)
        {
            string Constr = "server=.;database=db_test1;uid=sa;pwd=144159";
            conn = new SqlConnection(Constr);
            conn.Open();
        }
        private void button1_Click(object sender, EventArgs e)
        {
            try
            {
                if(conn.State==ConnectionState.Open||textBox1.Text !="")
                {
                    SqlCommand cmd = new SqlCommand();//创建SqlCommand对象
                    cmd.Connection = conn;//设置连接属性
                    cmd.CommandText = "select * from " + textBox1.Text.Trim();//设置sql语句
                    cmd.CommandType = CommandType.Text;//设置属性类型使其只执行sql语句文本形式
                    int i = Convert.ToInt32(cmd.ExecuteScalar());//调用方法获取数据数量
                    label2.Text = "数据表中共有:" + i.ToString() + "条数据";
                }
            }
            catch(Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

在这里插入图片描述
2.执行SQL语句
1)ExecuteNonQuery方法
对数据库中表的数据发生修改时,使用ExecuteNonQuery方法可以返回受影响的行数

SqlConnection conn;
        private void button1_Click(object sender, EventArgs e)
        {
            conn = new SqlConnection("server=.;database=db_test1;uid=sa;pwd=144159");
            conn.Open();
            SqlCommand cmd = new SqlCommand();
            cmd.Connection = conn;
            cmd.CommandText = "update db_table3 set 奖金=50 where 性别='女'";
            cmd.CommandType = CommandType.Text;
            int i = Convert.ToInt32(cmd.ExecuteNonQuery());
            label2.Text = "共有" + i.ToString() + "名女员工获得奖金";
        }

在这里插入图片描述
2)ExecuteReader方法
返回一个SqlDataReader对象

SqlDataReader sdr = cmd.ExecuteReader();//使用ExecuteReader方法实例化SqlDataReader对象
            while (sdr.Read())//调用while语句读取SqlDataReader
            {
                listView1.Items.Add(sdr[1].ToString());
            }

3)ExecuteScalar方法
返回结果集中第一行的第一列或空引用(如果结果集为空)
【读取数据:DataReader对象】
如果只需要快速读取数据,而不需要修改数据就可以用DataReader对象。
可以使用ExecuteReader方法。

SqlCommand cmd = new SqlCommand();
//使用ExecuteReader方法创建SqlDataReader对象
SqlDataReader sdr = cmd.ExecuteReader();

1.判断查询结果中是否有值
可以使用对象的HasRows属性获取一个值,来判断是否有值。

private void button1_Click(object sender, EventArgs e)
        {
            try
            {
                SqlConnection conn = new SqlConnection("server=.;database=db_15;uid=sa;pwd=");
                conn.Open();
                SqlCommand cmd = new SqlCommand("select * from "+textBox1.Text.Trim(), conn);
                SqlDataReader sdr = cmd.ExecuteReader();
                sdr.Read();//调用Read方法读取SqlDataReader
                if (sdr.HasRows)
                {
                    MessageBox.Show("数据表中有值");
                }
                else
                {
                    MessageBox.Show("数据表中没有任何数据");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }

在这里插入图片描述
2.读取数据
通过ExecuteReader方法创建SqlDataReader对象。对象调用Read方法,读取数据。
使用完,要用Close方法关闭SqlDataReader对象。

SqlCommand cmd = new SqlCommand();
SqlDataReader sdr = cmd.ExecuteReader();
sdr.Read();
sdr.Close();

【数据适配器:DataAdapter对象】
DataAdapter对象是一个数据适配器对象,是DataSet与数据源之间的桥梁。
有四个属性:
SelectCommand属性:向数据库发送查询SQL语句;
DeleteCommand属性:向数据库发送删除SQL语句;
InsertCommand属性:向数据库发送插入SQL语句;
UpdateCommand属性:向数据库发送更新SQL语句;
1.填充DataSet数据集
通过DataAdapter对象的Fill方法。

private void button1_Click(object sender, EventArgs e)
        {
            try
            {
                string Constr = "server=.;database=db_test1;uid=sa;pwd=144159";
                SqlConnection conn = new SqlConnection(Constr);
                conn.Open();
                SqlCommand cmd = new SqlCommand();
                cmd.Connection = conn;
                cmd.CommandText = "select * from db_table3";
                cmd.CommandType = CommandType.Text;
                SqlDataAdapter sda = new SqlDataAdapter();
                sda.SelectCommand = cmd;
                DataSet ds = new DataSet();
                sda.Fill(ds);
                dataGridView1.DataSource = ds.Tables[0];
            }
            catch(Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

在这里插入图片描述
2.更新数据源
使用DataAdapter对象的Update方法,可以将DataSet中修改过的数据更新到数据库中。在调用Update方法前,要实例化CommandBuilder类。

SqlConnection conn;
        DataSet ds;
        SqlDataAdapter sda;
        private void Form1_Load(object sender, EventArgs e)
        {
            conn = new SqlConnection("server=.;database=db_test1;uid=sa;pwd=144159");
            SqlCommand cmd = new SqlCommand("select * from db_table3", conn);
            sda = new SqlDataAdapter();
            sda.SelectCommand = cmd;
            ds = new DataSet();
            sda.Fill(ds,"cs");
            dataGridView1.DataSource = ds.Tables[0];
        }
        private void button1_Click(object sender, EventArgs e)
        {
            DataTable dt = ds.Tables["cs"];
            sda.FillSchema(dt, SchemaType.Mapped);
            DataRow dr = dt.Rows.Find(txtNo.Text);
            dr["奖金"] = txtjj.Text.Trim();
            dr["性别"] = this.txtSex.Text.Trim();
            SqlCommandBuilder cmdbuider = new SqlCommandBuilder(sda);
            sda.Update(dt);
        }
        private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            txtNo.Text = dataGridView1.SelectedCells[0].Value.ToString();
            txtjj.Text = dataGridView1.SelectedCells[2].Value.ToString();
            txtSex.Text = dataGridView1.SelectedCells[1].Value.ToString();
        }

在这里插入图片描述
【数据集:DataSet对象】
1.合并DataSet内容
可以使用DtaSet的Merge方法。将指定的DataSet及其架构与当前的DataSet合并。
2.复制DataSet内容
Copy方法。

DataSet ds1 = ds.Copy();

猜你喜欢

转载自blog.csdn.net/qq_43482627/article/details/91889035