1 using System; 2 using System.Collections.Generic; 3 using System.ComponentModel; 4 using System.Data; 5 using System.Drawing; 6 using System.Linq; 7 using System.Text; 8 using System.Threading.Tasks; 9 using System.Windows.Forms; 10 using System.Data.SqlClient; 11 12 namespace 餐厅 13 { 14 public partial class Form1 : Form 15 { 16 17 18 19 public Form1() 20 { 21 InitializeComponent(); 22 } 23 24 private void Form1_Load(object sender, EventArgs e) 25 { 26 LoadDeskInfoByDelFlag(0); 27 28 } 29 //数据库字符串 30 string str = "Data Source=.;Initial Catalog=mysql;Integrated Security=True"; 31 private void LoadDeskInfoByDelFlag(int p) 32 { 33 //查询 34 //新建集合 35 List<DeskInfo> list = new List<DeskInfo>(); 36 37 //sql语句,flag为0的餐桌 38 string sql = "select DeskId,DeskName,DeskNamePinYin,DeskNum from DeskInfo where DeskDelFlag = " + p; 39 //string sql = "select * from DeskInfo"; 40 SqlConnection con = new SqlConnection(str); 41 con.Open(); 42 SqlCommand cmd = new SqlCommand(sql, con); 43 //cmd.reader为查询 44 SqlDataReader reader = cmd.ExecuteReader(); 45 //判断是否读取了一行 46 if (reader.HasRows) 47 { 48 //当读取的时候 49 while (reader.Read()) 50 { 51 //实例化餐桌类,为每个属性赋值,值为数据库里的值,进行类型转换 52 DeskInfo dk = new DeskInfo(); 53 dk.DeskId = Convert.ToInt32(reader["DeskId"]); 54 dk.DeskName = reader["DeskName"].ToString(); 55 dk.DeskNamePinYin = reader["DeskNamePinYin"].ToString(); 56 dk.DeskNum = reader["DeskNum"].ToString(); 57 //把属性添加进list 58 list.Add(dk); 59 } 60 61 } 62 //禁止自动生成列,没有delflag那一列了。 63 dgv.AutoGenerateColumns = false; 64 //绑定数据 65 dgv.DataSource = list; 66 67 //关闭数据库各项 68 con.Dispose(); 69 cmd.Dispose(); 70 reader.Dispose(); 71 } 72 73 private void button1_Click(object sender, EventArgs e) 74 { 75 //增加餐桌 76 //sql语句 77 string sql = string.Format("insert into DeskInfo(DeskName, DeskNamePinYin, DeskDelFlag, DeskNum) values(‘{0}‘,‘{1}‘,0,‘{2}‘)", txtName.Text, txtPinYin.Text,txtNum.Text); 78 SqlConnection con = new SqlConnection(str); 79 con.Open(); 80 SqlCommand cmd = new SqlCommand(sql, con); 81 cmd.ExecuteNonQuery(); 82 LoadDeskInfoByDelFlag(0);//刷新 83 84 con.Dispose(); 85 cmd.Dispose(); 86 87 } 88 } 89 }
时间: 2024-10-05 18:59:41