Database basics
SQL is the abbreviation of Structured Query Language, which is translated into Chinese as "Structured Query Language". SQL is a computer language used to store, retrieve, and modify data stored in relational databases.
basic concept
1. Database (DataBase)
- A warehouse that organizes, stores and manages data according to a certain data structure. A collection of related data stored together.
2. Database Management System (DBMS)
- A computer software system designed for managing databases . We use SQL Server Management Studio from Microsoft
- It is divided into two types: relational database, which is a database based on the relational model, such as SqlServer MySQL Access Oracle; non-relational database: the difference is that it does not use SQL as the query language.
3. Database system
- It consists of database and database management system.
4. SQL is not case-sensitive, but it is better to write it in upper and lower cases separately.
Install
Database management system (DBMS), Microsoft SQL Server
DBMS is a set of services running in the background. To deal with this set of services, you need to download a client, that is, DBMS client, SQL server management studio, SSMS
Log in
Server=localhost\SQLEXPRESS;Database=master;Trusted_Connection=True;
前面是服务器名 后面是数据库名字
You can log in to c# directly from your computer like this. You can also log in like this inside.
Open remote connection
You can connect to the external network but cannot connect to your own computer.
1. You can first use Windows authentication to log in and check this box.
2. SQL Server Configuration Manager
3. Firewall
and then restart it
SQL
Database management system (DBMS), Microsoft SQL Server
DBMS is a set of services running in the background. To deal with this set of services, you need to download the client, that is, DBMS client, SQL server management studio, SSMS
Server=localhost \SQLEXPRESS;Database=master;Trusted_Connection=True;
Create a new database
Create new table
Set primary key
ctrl s save
Check for phrases
select * from t_user where id='1001' and psw='1'
Insert data
Those 3 and 10 are int types, so it doesn’t matter if we don’t use single quotes.
insert into t_book values('20190101','计算机系统原理','王万森','高等教育出版社','10'),('20190102','机械设计原理','董永','北京教育出版社','3')
select * from t_book
Another way to insert. I tried it later and it didn’t matter if I didn’t add []. It seems that the standard requires [ ] to be added to each item.
insert into t_lend ([uid],bid,name,[datetime]) values('2046','20190101','小明',getdate());
update t_book set number=number-1 where id='20190101'
select *from t_lend
select *from t_book
The following settings will automatically increase
renew
update t_book set id='111',[name]='高等数学',author='李四',number=100 where id='999'
select * from t_book
When you want to set an item in a table to be incremented
delete
delete from t_lend where [no]=5;
update t_book set number=number+1 where id='20190101'
select *from t_lend
select *from t_book
multi-line search
Delete multiple lines
delete from t_lend where [no] in('6','7')
select *from t_lend
select *from t_book
Database Design
c#programming
Dao.cs
Encapsulates functions that communicate with sql
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.SqlClient;
namespace WindowsFormsApp1
{
class Dao
{
SqlConnection con;
public SqlConnection connect()
{
//数据库连接字符串
//string str = @"Data Source=localhost\SQLEXPRESS;Initial Catalog = BookDB;Integrated_Security=True";//Data Source:服务器的名称;Initial Catalog:数据库的名称
string str = @"Data Source=localhost\SQLEXPRESS;Database = BookDB; Trusted_Connection = True;";//也就是我们安装的时候返回的连接字符串 然后将数据库的名字修改了下
con = new SqlConnection(str);//创建数据库连接对象
con.Open();//打开数据库
return con;//返回数据库连接对象
}
//sql:sql语句
public SqlCommand command(string sql)
{
SqlCommand cmd = new SqlCommand(sql,connect());
return cmd;
}
//更新操作
public int Execute(string sql)
{
return command(sql).ExecuteNonQuery();
}
//读取操作
public SqlDataReader read(string sql)
{
return command(sql).ExecuteReader();//首先执行的是command这个函数 然后返回cmd 再cmd.ExecuteReader()
}
//关闭数据库连接
public void Close()
{
con.Close();
}
}
}
Data.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace WindowsFormsApp1
{
class Data
{
public static string UID = "", UName = "";//登录用户的ID 和姓名
}
}
log in page
That is to verify whether the entered data exists in the t_user and t_admin tables (both account and password must be met), and if it exists, the page will be redirected.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
Core code login method
//登录方法,验证是否允许登录
public void login()
{
//用户
if(UserradioButton1.Checked==true)
{
Dao dao = new Dao();//实例化
//查询语句 拼成这样:select * from t_user where id='1001' and psw='1'
//string sql = "select * from t_user where id='"+ textBox1.Text +"' and psw='"+textBox2.Text+"'";//写法1
//string sql=string.Format("select * from t_user where id='{0}' and psw='{1}'",textBox1.Text,textBox2.Text);//写法2
string sql = $"select * from t_user where id='{
textBox1.Text}' and psw='{
textBox2.Text}'";//写法3
log.SaveLog(sql);
IDataReader dc = dao.read(sql);
//log.SaveLog(dc[0].ToString()+dc["name"].ToString());//第一行
if (dc.Read())//如果读到一行数据了 就返回真
{
//把值存好
Data.UID = dc["id"].ToString();
Data.UName=dc["name"].ToString();
MessageBox.Show("登录成功");
UserFrm userFrm = new UserFrm();
this.Hide();
userFrm.Show();
}
else
{
MessageBox.Show("登录失败");
}
dao.Close();
}
//管理员
if(AdmiradioButton2.Checked==true)
{
Dao dao = new Dao();//实例化
string sql = $"select * from t_admin where id='{
textBox1.Text}' and psw='{
textBox2.Text}'";//写法3
log.SaveLog(sql);
IDataReader dc = dao.read(sql);
if (dc.Read())//如果读到一行数据了 就返回真
{
//把值存好
Data.UID = dc["id"].ToString();
// Data.UName=dc["name"].ToString();
MessageBox.Show("登录成功");
//log.SaveLog(dc[0].ToString() + dc["name"].ToString());//第一行
AdminFrm frm= new AdminFrm();
this.Hide();
frm.ShowDialog();
}
else
{
MessageBox.Show("登录失败");
}
dao.Close();
}
//MessageBox.Show("单选框请先选中");
}
Login button
private void button1_Click(object sender, EventArgs e)
{
if(textBox1.Text!="" && textBox2.Text!="")
{
login();
}
else
{
MessageBox.Show("输入有空项,请输入");
}
}
Administrator homepage
Mainly performs a jump function and then adds a close callback function to exit the program when the page is closed.
public AdminFrm()
{
InitializeComponent();
this.FormClosing += new FormClosingEventHandler(this.NI_FormClosing);
}
private void NI_FormClosing(object sender, FormClosingEventArgs e)
{
Application.Exit();
}
private void 图书管理ToolStripMenuItem_Click(object sender, EventArgs e)
{
BookManageFrm frm = new BookManageFrm();
frm.ShowDialog();
}
Book management page
That is to say, operate the data in t_book to add a row, modify a row, delete a row, and then find a certain row in it
to obtain the book data function.
//从数据库读取数据显示在表格控件中
public void Fresh()
{
dataGridView1.Rows.Clear();//清空旧数据
Dao dao = new Dao();
string sql = "select * from t_book";
IDataReader dc = dao.read(sql);
string a0,a1, a2,a3, a4,a5;
//dc.Read():一行一行的读 读到没有了就会返回一个false
while (dc.Read())
{
//dataGridView1.Rows.Add(dc[0].ToString(), dc[1].ToString(), dc[2].ToString(), dc[3].ToString(), dc[4].ToString());
//下面这样写和上面这样写 效果是一样的
a0 = dc[0].ToString();
a1 = dc[1].ToString();
a2 = dc[2].ToString();
a3 = dc[3].ToString();
a4 = dc[4].ToString();
string[] table = {
a0,a1,a2,a3,a4};
dataGridView1.Rows.Add(table);
}
//关闭 System.Data.IDataReader 对象。
dc.Close();
//关闭数据库连接
dao.Close();
}
Query function based on id
//根据ID查询
public void InquireId()
{
dataGridView1.Rows.Clear();//清空旧数据
Dao dao = new Dao();
string sql = $"select * from t_book where id='{
textBox1.Text}'";
IDataReader dc = dao.read(sql);
string a0, a1, a2, a3, a4, a5;
//dc.Read():一行一行的读 读到没有了就会返回一个false
while (dc.Read())
{
//dataGridView1.Rows.Add(dc[0].ToString(), dc[1].ToString(), dc[2].ToString(), dc[3].ToString(), dc[4].ToString());
//下面这样写和上面这样写 效果是一样的
a0 = dc[0].ToString();
a1 = dc[1].ToString();
a2 = dc[2].ToString();
a3 = dc[3].ToString();
a4 = dc[4].ToString();
string[] table = {
a0, a1, a2, a3, a4 };
dataGridView1.Rows.Add(table);
}
//关闭 System.Data.IDataReader 对象。
dc.Close();
//关闭数据库连接
dao.Close();
}
Query function based on book title
//根据书名查询 模糊查询
public void InquireName()
{
dataGridView1.Rows.Clear();//清空旧数据
Dao dao = new Dao();
string sql = $"select * from t_book where name like '%{
textBox2.Text}%'";
IDataReader dc = dao.read(sql);
string a0, a1, a2, a3, a4, a5;
//dc.Read():一行一行的读 读到没有了就会返回一个false
while (dc.Read())
{
//dataGridView1.Rows.Add(dc[0].ToString(), dc[1].ToString(), dc[2].ToString(), dc[3].ToString(), dc[4].ToString());
//下面这样写和上面这样写 效果是一样的
a0 = dc[0].ToString();
a1 = dc[1].ToString();
a2 = dc[2].ToString();
a3 = dc[3].ToString();
a4 = dc[4].ToString();
string[] table = {
a0, a1, a2, a3, a4 };
dataGridView1.Rows.Add(table);
}
//关闭 System.Data.IDataReader 对象。
dc.Close();
//关闭数据库连接
dao.Close();
}
BookManageFrm_Load
private void BookManageFrm_Load(object sender, EventArgs e)
{
Fresh();
string id = dataGridView1.SelectedRows[0].Cells[0].Value.ToString();//选中的第0行 第0个单元格 也就是书号(主键)
label2.Text = id + dataGridView1.SelectedRows[0].Cells[1].Value.ToString();//书名+书号
}
Add book button
AddBookFrm frm=new AddBookFrm();
frm.ShowDialog();//打开增加图书页面
Fresh();//刷新页面
Modify book button, display the modify book page and pass parameters into it
try
{
string id= dataGridView1.SelectedRows[0].Cells[0].Value.ToString();//选中的第0行 第0个单元格 也就是书号(主键)
string name = dataGridView1.SelectedRows[0].Cells[1].Value.ToString();//选中的第0行 第0个单元格 也就是书号(主键)
string author = dataGridView1.SelectedRows[0].Cells[2].Value.ToString();//选中的第0行 第0个单元格 也就是书号(主键)
string press = dataGridView1.SelectedRows[0].Cells[3].Value.ToString();//选中的第0行 第0个单元格 也就是书号(主键)
string number = dataGridView1.SelectedRows[0].Cells[4].Value.ToString();//选中的第0行 第0个单元格 也就是书号(主键)
AltBookFrm altBookFrm = new AltBookFrm(id,name,author,press,number);
altBookFrm.ShowDialog();
Fresh();//刷新数据
}
catch
{
MessageBox.Show("error");
}
Delete book
try
{
string id = dataGridView1.SelectedRows[0].Cells[0].Value.ToString();//选中的第0行 第0个单元格 也就是书号(主键)
DialogResult dr=MessageBox.Show("确认删除吗?","信息提示",MessageBoxButtons.OKCancel,MessageBoxIcon.Question);
if(dr==DialogResult.OK)
{
string sql = $"delete from t_book where id='{
id}'";
Dao dao =new Dao();
if(dao.Execute(sql)>0)
{
MessageBox.Show("删除成功");
Fresh();
}
else
{
MessageBox.Show("删除失败");
}
dao.Close();
}
}
catch
{
MessageBox.Show("请先在表格选中要删除的图书记录","信息提示",MessageBoxButtons.OK,MessageBoxIcon.Error);
}
refresh
private void button4_Click(object sender, EventArgs e)
{
Fresh();
textBox1.Text = "";
textBox2.Text = "";
}
For book number query and book title query, just call the above function.
private void button5_Click(object sender, EventArgs e)
{
InquireId();
}
private void button6_Click(object sender, EventArgs e)
{
InquireName();
}
Delete multiple lines
int n = dataGridView1.SelectedRows.Count;//获取当前选中的行数
string sql = $"delete from t_book where id in (";
for(int i = 0; i < n; i++)
{
sql += $"'{
dataGridView1.SelectedRows[i].Cells[0].Value.ToString()}',";
}
sql = sql.Remove(sql.Length - 1);//删除最后一个字符 因为是从0开始计的
sql += ")";
log.SaveLog(sql);
Dao dao = new Dao();
if(dao.Execute(sql)>n-1)//受影响的行数大于n-1
{
MessageBox.Show($"成功删除{
n}条图书信息");
Fresh();
}
Add book page
Add book button
if(textBox1.Text!=""&& textBox2.Text != "" && textBox3.Text != "" && textBox4.Text != "" && textBox5.Text != "")
{
Dao dao = new Dao();
string sql = $"insert into t_book values('{
textBox1.Text}','{
textBox2.Text}','{
textBox3.Text}','{
textBox4.Text}','{
textBox5.Text}')";
int n =dao.Execute(sql);
if(n> 0)
{
MessageBox.Show("添加成功");
}
else
{
MessageBox.Show("添加失败");
}
textBox1.Text = "";
textBox2.Text = "";
textBox3.Text = "";
textBox4.Text = "";
textBox5.Text = "";
}
else
{
MessageBox.Show("输入不允许空");
}
clear button
textBox1.Text = "";
textBox2.Text = "";
textBox3.Text = "";
textBox4.Text = "";
textBox5.Text = "";
Edit book page
string ID = "";//登录用户的ID 刚登录的时候就保存在data.cs中
Then create a constructor with parameters to receive the passed parameters
public AltBookFrm()
{
InitializeComponent();
}
public AltBookFrm(string id,string name,string author,string press,string number)
{
InitializeComponent();
ID =textBox1.Text = id;
textBox2.Text = name;
textBox3.Text = author;
textBox4.Text = press;
textBox5.Text = number;
}
Modify button
string sql = $"update t_book set id='{
textBox1.Text}',[name]='{
textBox2.Text}',author='{
textBox3.Text}',press='{
textBox4.Text}',number={
textBox5.Text} where id='{
ID}'";
Dao dao = new Dao();
if(dao.Execute(sql)>0)
{
MessageBox.Show("修改成功");
}
User page
Make a jump to close this page to close the application.
Close to exit.
public UserFrm()
{
InitializeComponent();
label1.Text = $"欢迎{
Data.UName}登录";
this.FormClosing += new FormClosingEventHandler(this.NI_FormClosing);
}
private void NI_FormClosing(object sender, FormClosingEventArgs e)
{
Application.Exit();
}
Just make a jump
private void 当前借出图书和归还ToolStripMenuItem_Click(object sender, EventArgs e)
{
UserBookCheckFrm u=new UserBookCheckFrm();
u.Show();
}
private void 图书归还ToolStripMenuItem_Click_1(object sender, EventArgs e)
{
UserBookCondition userc=new UserBookCondition();
userc.Show();
}
View books and borrow
The actual operation is the two pages t_lend and t_book. The t_lend page adds a row of data. The number + 1 in t_book. Book number query and book title query are refreshed
on the book management page.
public void Fresh()
{
dataGridView1.Rows.Clear();//清空旧数据
Dao dao = new Dao();
string sql = "select * from t_book";
IDataReader dc = dao.read(sql);
string a0, a1, a2, a3, a4, a5;
//dc.Read():一行一行的读 读到没有了就会返回一个false
while (dc.Read())
{
//dataGridView1.Rows.Add(dc[0].ToString(), dc[1].ToString(), dc[2].ToString(), dc[3].ToString(), dc[4].ToString());
//下面这样写和上面这样写 效果是一样的
a0 = dc[0].ToString();
a1 = dc[1].ToString();
a2 = dc[2].ToString();
a3 = dc[3].ToString();
a4 = dc[4].ToString();
string[] table = {
a0, a1, a2, a3, a4 };
dataGridView1.Rows.Add(table);
}
//关闭 System.Data.IDataReader 对象。
dc.Close();
//关闭数据库连接
dao.Close();
}
Check out book button
string id = dataGridView1.SelectedRows[0].Cells[0].Value.ToString();//获取书号
string name = dataGridView1.SelectedRows[0].Cells[1].Value.ToString();
int number=int.Parse(dataGridView1.SelectedRows[0].Cells[4].Value.ToString());//库存
if(number<1)
{
MessageBox.Show("库存不足");
}
else
{
string sql = $"insert into t_lend ([uid],bid,name,[datetime]) values('{
Data.UID}','{
id}','{
name}',getdate());update t_book set number=number-1 where id='{
id}'";
Dao dao = new Dao();
if(dao.Execute(sql)>1)//因为sql里面包含了两条语句
{
MessageBox.Show($"{
Data.UName}借书成功");
Fresh();
}
}
Book borrowing status and return page
The actual operation is the two pages t_lend and t_book. The t_lend page reduces one row of data, and the number of numbers in t_book
is returned +1.
string no = dataGridView1.SelectedRows[0].Cells[0].Value.ToString();
string bookid = dataGridView1.SelectedRows[0].Cells[1].Value.ToString();
string sql = $"delete from t_lend where[no] = {
no}; update t_book set number = number + 1 where id = '{
bookid}'";
Dao dao = new Dao();
if(dao.Execute(sql)>1)
{
MessageBox.Show("归还成功");
Fresh();
}
refresh
public void Fresh()
{
dataGridView1.Rows.Clear();//清空旧数据
Dao dao = new Dao();
string sql = $"select *from t_lend where [uid]='{
Data.UID}'";
IDataReader dc = dao.read(sql);
string a0, a1, a2, a3, a4, a5;
//dc.Read():一行一行的读 读到没有了就会返回一个false
while (dc.Read())
{
//dataGridView1.Rows.Add(dc[0].ToString(), dc[1].ToString(), dc[2].ToString(), dc[3].ToString(), dc[4].ToString());
//下面这样写和上面这样写 效果是一样的
a0 = dc[0].ToString();
a1 = dc[1].ToString();
a2 = dc[2].ToString();
a3 = dc[3].ToString();
a4 = dc[4].ToString();
string[] table = {
a0, a2, a3, a4 };
dataGridView1.Rows.Add(table);
}
//关闭 System.Data.IDataReader 对象。
dc.Close();
//关闭数据库连接
dao.Close();
}
References
Install
a very good video
SQL
tutorial
source code
to learn MySQL. This article is enough.