开发工具 VS 2022 C#,数据库MS SQL SERVER 2019
1.WinForms界面
2.使用SqlDataApater + DataSet + DataGridView 读取数据
private void ReadData()
{//数据库连接串string strConn = "Data Source=127.0.0.1;Initial Catalog=TEST;Persist Security Info=True;User ID=sa;Password=*********;Encrypt=False";SqlConnection conn = null;try{conn = new SqlConnection(strConn);conn.Open();//打开数据库string sql = "select * from TestTask order by 1";SqlDataAdapter sda = new SqlDataAdapter(sql, conn); //创建SqlDataAdapter类的对象System.Data.DataSet ds = new System.Data.DataSet();//创建DataSet类的对象sda.Fill(ds);//使用SqlDataAdapter对象sda将查新结果填充到DataSet对象ds中dataGridView1.DataSource = ds.Tables[0];//设置表格控件的DataSource属性//设置数据表格上显示的列标题//dataGridView1.Columns[0].HeaderText = "编号";//设置数据表格为只读dataGridView1.ReadOnly = true;//不允许添加行dataGridView1.AllowUserToAddRows = false;//背景为白色dataGridView1.BackgroundColor = Color.White;//只允许选中单行dataGridView1.MultiSelect = false;//整行选中dataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect;}catch (Exception ex){MessageBox.Show("加载数据错误!" + ex.Message);}finally{if (conn != null){conn.Close();//关闭数据库连接}}
}
3.根据查询条件查询数据
if (textBox1.Text != "")//textBox1.Text为查询条件
{string strConn = "Data Source=127.0.0.1;Initial Catalog=TEST;Persist Security Info=True;User ID=sa;Password=********;Encrypt=False";//创建SqlConnection的实例SqlConnection conn = null;try{conn = new SqlConnection(strConn);conn.Open(); //打开数据库string sql = "select * from TestTask where 检测编号 like '%{0}%'";sql = string.Format(sql, textBox1.Text);/填充占位符SqlDataAdapter sda = new SqlDataAdapter(sql, conn);//创建SqlDataAdapter类的对象DataSet ds = new DataSet();//创建DataSet类的对象sda.Fill(ds);//使用SqlDataAdapter对象sda将查新结果填充到DataSet对象ds中dataGridView1.DataSource = ds.Tables[0];//设置表格控件的DataSource属性}catch (Exception ex){MessageBox.Show("查询数据出错!" + ex.Message);}finally{if (conn != null){//关闭数据库连接conn.Close();}}
}
4.更新数据