本周周一和周四分别进行了编译原理和设计模式的考试,随着考试结束这两门课程的知识暂且放下了。第17周有几门课程需要验收大作业,因此需要做一做。
周末这段时间我重学了一遍.NET编程,并使用C#自己编写了一个简易的图书管理系统,总代码行数500左右,因为使用C#编程时界面直接调用控件排列即可,所以需要编写的地方只需要后台连接数据库和页面传参等等。下面给出一些代码片段和截图。
查询与删除:
private void button1_Click(object sender, EventArgs e) { if (textBox1.Text == "") { MessageBox.Show("查询条件不能为空!"); } else { string connsqlserver = "Data Source=LAPTOP-983LEFQ7;Initial Catalog=BOOK;User ID=sa;Pwd=Yuyuko"; string sql = ""; if (kind == "all") { sql = "select * from books where bookname like '%{0}%'"; } else { sql = "select * from books where bookname like '%{0}%' and bookkind='" + kind + "'"; } SqlConnection conn = new SqlConnection(connsqlserver); conn.Open(); try { sql = string.Format(sql, textBox1.Text); SqlDataAdapter sda = new SqlDataAdapter(sql, conn); DataSet ds = new DataSet(); sda.Fill(ds); dataGridView1.DataSource = ds.Tables[0]; } catch (Exception msg) { MessageBox.Show("查询错误!" + msg.Message); } finally { conn.Close(); } } } private void button2_Click(object sender, EventArgs e) { string bookid = dataGridView1.SelectedRows[0].Cells[0].Value.ToString(); string bookfrom = dataGridView1.SelectedRows[0].Cells[4].Value.ToString(); if (bookfrom != username) { MessageBox.Show("不可删除其他用户上传的书!"); } else { if (MessageBox.Show("确认删除么?", "确认", MessageBoxButtons.YesNo) == DialogResult.Yes) { string connsqlserver = "Data Source=LAPTOP-983LEFQ7;Initial Catalog=BOOK;User ID=sa;Pwd=Yuyuko"; string sql = "delete from books where bookid='" + bookid + "'"; SqlConnection conn = new SqlConnection(connsqlserver); conn.Open(); try { SqlCommand cmd = new SqlCommand(sql, conn); int res = cmd.ExecuteNonQuery(); if (res > 0) { MessageBox.Show("删除成功!"); this.kind = "all"; QueryAllBook(); } else { MessageBox.Show("删除失败!"); } } catch (Exception msg) { MessageBox.Show("删除错误!" + msg.Message); } finally { conn.Close(); } } } }
遍历:
private void QueryAllBook() { string connsqlserver = "Data Source=LAPTOP-983LEFQ7;Initial Catalog=BOOK;User ID=sa;Pwd=Yuyuko"; string sql = ""; if (kind == "all") { sql = "select * from books"; } else { sql = "select * from books where bookkind='" + kind + "'"; } SqlConnection conn = new SqlConnection(connsqlserver); conn.Open(); try { SqlDataAdapter sda = new SqlDataAdapter(sql, conn); DataSet ds = new DataSet(); sda.Fill(ds); dataGridView1.DataSource = ds.Tables[0]; dataGridView1.Columns[0].HeaderText = "书籍编号"; dataGridView1.Columns[1].HeaderText = "书籍名称"; dataGridView1.Columns[2].HeaderText = "书籍种类"; dataGridView1.Columns[3].HeaderText = "书籍简介"; dataGridView1.Columns[4].HeaderText = "上传用户"; dataGridView1.ReadOnly = true; dataGridView1.AllowUserToAddRows = false; dataGridView1.MultiSelect = false; dataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect; } catch(Exception msg) { MessageBox.Show("遍历错误!" + msg.Message); } finally { conn.Close(); } }
添加与修改的代码与上述类似,本质上都是使用SQL语句,这次进行数据操作所使用的数据库为SQLServer数据库,平时写JavaWeb的时候用的是MySQL。
界面做得很简陋,不过基本的增删改查都有。