15小项目 连接数据库+读取信息
1.新建项目:

2.头文件:
using System;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.Data;
namespace WindowsFormsApp1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
comboBox1.SelectedIndex = 0;// 默认选中第一项
comboBox2.SelectedIndex = 0;
//必须先创建表头
listView1.Columns.Add("员工号", listView1.Width / 2 - 1, HorizontalAlignment.Left);
listView1.Columns.Add("员工姓名", listView1.Width / 2 - 1, HorizontalAlignment.Left);
}
private void button1_Click(object sender, EventArgs e)
{
string connStr = "Data Source=DESKTOP-CHKF0KA;Initial Catalog=temp;Integrated Security=True";//使用windows连接
//DESKTOP-CHKF0KA 连接的数据库服务器名
//temp 数据库名字
SqlConnection conn = new SqlConnection(connStr);
conn.Open();
if (conn.State == ConnectionState.Open)
{
//MessageBox.Show("数据库连接成功!");//winform中可以用
Console.WriteLine("连接成功");//控制台用
}
string t1 = comboBox1.Text;//EmpNo
string sql = String.Format("select * from works w join employee e on w.EmpNo = e.EmpNo " +
"join company c on w.CmpNo = c.CmpNo " +
"where e.EmpNo = '{0}'",t1);//EmpName = '{0}' and t1,
SqlCommand cmd = new SqlCommand(sql, conn);
listView1.Items.Clear();
try
{
SqlDataReader re = cmd.ExecuteReader();//.ExecuteNonQuery();
Console.WriteLine("修改成功");
if (!re.HasRows)//判断是否为空
{
comboBox1.Text = "不存在该员工";
return;
}
//re.Read();
//textBox1.Text = re["EmpName"].ToString();
this.listView1.BeginUpdate(); //数据更新,UI暂时挂起,直到EndUpdate绘制控件,可以有效避免闪烁并大大提高加载速度
for (int i = 0; re.Read(); i++) //添加10行数据
{
ListViewItem lvi = new ListViewItem();//放入表中
lvi.Text = re["EmpNo"].ToString();
lvi.SubItems.Add(re["EmpName"].ToString());
lvi.SubItems.Add(re["EmpSex"].ToString());
lvi.SubItems.Add(re["EmpAge"].ToString());
this.listView1.Items.Add(lvi);
//listView1.Text += re["EmpNo"].ToString();
}
this.listView1.EndUpdate(); //结束数据处理,UI界面一次性绘制。
}
catch (SqlException ae)
{
Console.WriteLine("修改失败");
Console.WriteLine(ae.Message);
MessageBox.Show("error");
}
finally
{
conn.Close();//对数据库操作完成后,需要关闭数据库,释放内存
}
}