데이터베이스 기본 사항
SQL은 Structured Query Language의 약어로, 중국어로 "Structured Query Language"로 번역됩니다. SQL은 관계형 데이터베이스에 저장된 데이터를 저장, 검색 및 수정하는 데 사용되는 컴퓨터 언어입니다.
기본 사상
1. 데이터베이스(DataBase)
- 특정 데이터 구조에 따라 데이터를 정리, 저장, 관리하는 창고입니다. 함께 저장된 관련 데이터의 모음입니다.
2. 데이터베이스 관리 시스템(DBMS)
- 데이터베이스 관리를 위해 설계된 컴퓨터 소프트웨어 시스템 입니다 . 우리는 Microsoft의 SQL Server Management Studio를 사용합니다.
- SqlServer MySQL Access Oracle과 같은 관계형 모델을 기반으로 하는 데이터베이스인 관계형 데이터베이스와 쿼리 언어로 SQL을 사용하지 않는 비관계형 데이터베이스의 두 가지 유형으로 나뉩니다.
3. 데이터베이스 시스템
- 데이터베이스와 데이터베이스 관리 시스템으로 구성됩니다.
4. SQL은 대소문자를 구분하지 않으나 대문자와 소문자를 구분하여 작성하는 것이 좋습니다.
설치하다
데이터베이스 관리 시스템(DBMS), Microsoft SQL Server
DBMS는 백그라운드에서 실행되는 서비스 집합입니다. 이 서비스 집합을 처리하려면 클라이언트, 즉 DBMS 클라이언트, SQL 서버 관리 스튜디오, SSMS를 다운로드해야 합니다.
로그인
Server=localhost\SQLEXPRESS;Database=master;Trusted_Connection=True;
前面是服务器名 后面是数据库名字
컴퓨터에서 직접 C#에 로그인할 수도 있고, 내부에서도 로그인할 수 있습니다.
원격 연결 열기
외부 네트워크에 연결할 수 있지만 자신의 컴퓨터에 연결할 수 없습니다..
1. 먼저 Windows 인증을 사용하여 로그인하고 이 상자를 선택할 수 있습니다.
2. SQL Server 구성 관리자
3. 방화벽을
설치한 후 다시 시작하세요.
SQL
데이터베이스 관리 시스템(DBMS), Microsoft SQL Server
DBMS는 백그라운드에서 실행되는 서비스 집합입니다. 이 서비스 집합을 처리하려면 클라이언트, 즉 DBMS 클라이언트, SQL 서버 관리 스튜디오, SSMS
서버를 다운로드해야 합니다. localhost\SQLEXPRESS;데이터베이스=마스터;Trusted_Connection=True;
새 데이터베이스 만들기
새 테이블 만들기
기본 키 설정
Ctrl S 저장
문구를 확인하세요
select * from t_user where id='1001' and psw='1'
데이터 삽입
3과 10은 int 유형이므로 작은따옴표를 사용하지 않아도 문제가 되지 않습니다.
insert into t_book values('20190101','计算机系统原理','王万森','高等教育出版社','10'),('20190102','机械设计原理','董永','北京教育出版社','3')
select * from t_book
삽입하는 또 다른 방법인데 나중에 시도해 봤는데 []를 안 넣어도 상관없더라고요.. 표준에서는 각 항목에 []를 추가하도록 요구하는 것 같습니다.
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
다음 설정은 자동으로 증가합니다
고쳐 쓰다
update t_book set id='111',[name]='高等数学',author='李四',number=100 where id='999'
select * from t_book
테이블의 항목을 증가시키려는 경우
삭제
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
여러 줄 검색
여러 줄 삭제
delete from t_lend where [no] in('6','7')
select *from t_lend
select *from t_book
데이터베이스 설계
C#프로그래밍
Dao.cs
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 和姓名
}
}
로그인 페이지
이는 입력한 데이터가 t_user, t_admin 테이블에 존재하는지(계정과 비밀번호가 모두 일치해야 함) 확인하고 존재하는 경우 해당 페이지로 리디렉션됩니다.
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;
핵심코드 로그인 방법
//登录方法,验证是否允许登录
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("单选框请先选中");
}
로그인 버튼
private void button1_Click(object sender, EventArgs e)
{
if(textBox1.Text!="" && textBox2.Text!="")
{
login();
}
else
{
MessageBox.Show("输入有空项,请输入");
}
}
관리자 홈페이지
주로 점프 기능을 수행하며, 페이지가 닫힐 때 프로그램을 종료하는 닫기 콜백 함수를 추가합니다.
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();
}
도서 관리 페이지
즉, t_book의 데이터를 조작하여 행을 추가하고, 행을 수정하고, 행을 삭제한 후 그 안의 특정 행을 찾아
책 데이터 함수를 얻습니다.
//从数据库读取数据显示在表格控件中
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();
}
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();
}
책 제목 기반 쿼리 기능
//根据书名查询 模糊查询
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();//书名+书号
}
도서 추가 버튼
AddBookFrm frm=new AddBookFrm();
frm.ShowDialog();//打开增加图书页面
Fresh();//刷新页面
책 수정 버튼, 책 수정 페이지 표시 및 매개변수 전달
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");
}
책 삭제
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);
}
새로 고치다
private void button4_Click(object sender, EventArgs e)
{
Fresh();
textBox1.Text = "";
textBox2.Text = "";
}
도서 번호 조회, 도서 제목 조회는 위 함수를 호출하면 됩니다.
private void button5_Click(object sender, EventArgs e)
{
InquireId();
}
private void button6_Click(object sender, EventArgs e)
{
InquireName();
}
여러 줄 삭제
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();
}
도서 페이지 추가
도서 추가 버튼
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("输入不允许空");
}
지우기 버튼
textBox1.Text = "";
textBox2.Text = "";
textBox3.Text = "";
textBox4.Text = "";
textBox5.Text = "";
도서 페이지 수정
string ID = "";//登录用户的ID 刚登录的时候就保存在data.cs中
그런 다음 전달된 매개변수를 수신하기 위해 매개변수가 있는 생성자를 만듭니다.
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;
}
수정 버튼
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("修改成功");
}
사용자 페이지
응용 프로그램을 닫으려면 이 페이지를 닫으십시오.
종료하려면 닫으십시오.
public UserFrm()
{
InitializeComponent();
label1.Text = $"欢迎{
Data.UName}登录";
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)
{
UserBookCheckFrm u=new UserBookCheckFrm();
u.Show();
}
private void 图书归还ToolStripMenuItem_Click_1(object sender, EventArgs e)
{
UserBookCondition userc=new UserBookCondition();
userc.Show();
}
책보기 및 대출
실제 작업은 t_lend와 t_book 두 페이지입니다. t_lend 페이지는 데이터 행을 추가합니다. t_book의 숫자 + 1.
도서 관리 페이지에서 도서 번호 쿼리 및 도서 제목 쿼리가
새로 고쳐 집니다.
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();
}
예약 버튼 확인
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();
}
}
도서대출현황 및 반납페이지
실제 연산은 t_lend와 t_book 두 페이지이며, t_lend 페이지는 데이터 한 행을 줄이고 t_book에 있는 숫자의 개수는 +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();
}
새로 고치다
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();
}