(七)ADO.NET用窗体应用程序写增删查改——查(1.1升级版)

在1.0版本中,我们的程序只能做到单条查询,在此升级了下,通过多种方式查询,紧接前面两节“增”、“删”代码。

一、通过输入数据库表名进行查询并统计表中数据

点击“查询”进入Click事件编写代码如下,

        private void button1_Click(object sender, EventArgs e)//按数据库查询
        {
            try
            {
                SqlConnection conn = new SqlConnection("server=.;database=MyDatabaseOne;user=sa;pwd=35683568");
                conn.Open();
                SqlCommand cmd = new SqlCommand();//创建对象
                cmd.Connection = conn;
                cmd.CommandText = "select count(*) from " + textuser.Text.Trim();
                cmd.CommandType = CommandType.Text;
                int i = Convert.ToInt32(cmd.ExecuteScalar());
                lbdata.Text = "数据库表中共有" + i.ToString() + "条数据";
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }

        }

运行结果如下:

二、通过输入姓名查询并显示数据

点击“查询”进入Click事件编写代码如下,

        private void button2_Click(object sender, EventArgs e)//按字段查询
        {
            //创建连接字符串
            SqlConnection conn = new SqlConnection("server=.;database=MyDatabaseOne;user=sa;pwd=35683568");
            conn.Open();
            string sqlstring = "select * from users where name='" + this.textfiled.Text.Trim() + "'";
            DataTable dt = new DataTable();
            SqlCommand cmd = new SqlCommand(sqlstring, conn);
            try
            {
                dt.Load(cmd.ExecuteReader(CommandBehavior.CloseConnection));
            }
            catch(Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            this.dataGridView1.DataSource = dt;
        }

运行结果如下:

三、查询所有数据

点击“查询”进入Click事件编写代码如下,

        private void bntSelect_Click(object sender, EventArgs e)//查询所有数据
        {
            //创建连接字符串
            SqlConnection conn = new SqlConnection("server=.;database=MyDatabaseOne;user=sa;pwd=35683568");
            conn.Open();
            SqlCommand cmd = new SqlCommand("select * from users", conn);
            SqlDataAdapter sda = new SqlDataAdapter(cmd);
            DataSet ds = new DataSet();
            sda.Fill(ds);
            DataTable dt = ds.Tables[0];
            dataGridView1.AutoGenerateColumns = false;
            dataGridView1.DataSource = ds.Tables[0];
            conn.Close();
        }

运行结果如下:

posted @ 2024-02-28 15:34  代号六零一  阅读(9)  评论(0编辑  收藏  举报