当前位置:网站首页>C # homework - student information management system
C # homework - student information management system
2022-06-10 16:01:00 【Mo fan-11】
Catalog
- One 、 Database operation
- Two 、 Multi meter operation
- 3、 ... and 、 Login operation
- Four : Menu operation
- 5、 ... and : Echo data
- 6、 ... and 、 Modify delete data
- 7、 ... and 、 Value transfer between pages
One 、 Database operation
Build database structure
1: Create a new database
1: open Database management software navicat/SQLoya
2: Create connection
3: Select connect and right-click to create a new database
4: Expand the database
5: Right click new table
2: The data in the table
Unique ID: Identification of this table It's like an ID card only .
id: Generally, we use it as the primary key ( Non empty 、 Self increasing )
3: Populating data in a table
When creating a new table : Each field has a type
When we fill in the data : To populate data by type
int: Integers Such as :1、2、3、…
varchar: character string ( Length... Must be specified ) Such as :‘ stupid ’、‘ Simon blow snow ’、…
Table structure display 
Basic operations on data ( add to modify Delete Inquire about )
Now add data to the table , Then we show the list and query
1: newly added
grammar :INSEST INTO + Table name ( Field name 1, Field name 2, Field 3...) VALUES( list 1, list 2,...)
Return value : Affected lines ( When adding, deleting and modifying , Will return the affected data )
Add a new student because sid Self increasing We do not need to add a primary key every time we add data ; because sid It will automatically add .
INSERT INTO student (sname, sage) VALUES(" Zhou Zhiruo ", 19)
Add more data
INSERT INTO student (sname, sage) VALUES(' Monday ', 18),(' Tuesday ', 19),(' Wednesday ', 20)
2: modify
grammar :UPDATE + Table name set Name = ' The new data ' where Conditions
hold id by 1 Name of the person Change to Zhang San
update student set sname=' Zhang San ' where sid=1
Put the name of Monday Change to Friday
update student set sname=' Sunday ' where sname=' Monday '
3: Delete
grammar :DELETE from Table name + WHERE Conditions
Delete student ID as 1 Of the students
DELETE FROM student WHERE sid = 1
In real development , Deletion is not a physical deletion It's logical deletion ( That is, a variable is used to indicate whether it is deleted )
4: Inquire about Single table 、 Multi table query
grammar :SELECT < Fields to query sage/sid/ All (*)> from + Table name where Conditions
Query all student information ( All the columns in the table )
SELECT * FROM student
Query student age and full name
SELECT sname, sage FROM student
Conditions of the query The age found is 18 The name of the person
SELECT sname FROM student WHERE sage=18
Multiple conditions The age of inquiry is 18 and The name is all the information about the person on Tuesday
SELECT * FROM student WHERE sage=18 AND sname=' Tuesday '
Fuzzy query Check all names with weeks
SELECT * FROM student WHERE sname LIKE '% Zhou %'
Why do I need to create an associated table ?
When we perform class operations , If we put the class in the student list, we may not be able to operate .
such as : Three 2020 The students in the class , Duplicate data found in query , Another example is the addition of 2025 class , But there are no students at this time 2025 class , What if I can't operate the student list . At this time, we can consider : Use association tables , Create a new class table .
C# WinForm Combined with database
Get the value of the data frame
// According to the properties of the component name obtain Input box (TextBox) The data in it
// this: The current window uses name: Property name Text: Text
string sname = this.sname.Text;
string sage = this.sage.Text;
The new data ( Connect to database + perform SQL sentence )
private void button1_Click(object sender, EventArgs e)
{
// According to the properties of the component name obtain Input box (TextBox) The data in it
// this: The current window uses name: Property name Text: Text
string sname = this.sname.Text;
string sage = this.sage.Text;
// Operation of connecting database
// 1: Declare a data source Purpose : Find my receipt bank
/* * server: service localhost/127.0.0.1( Local ) * port: Port number MySQL The port number of the database is 3306 So it fits * database: database Declare which database I want to use * uid: Database user name * pwd: Database password */
string url = "server=127.0.0.1; port=3306;database=csharp;uid=root;pwd=root";
// 2: establish link
// Be careful : When we link to the database, we need to reference mysql.data.dll
MySqlConnection con = new MySqlConnection(url);
// 3: Open database
con.Open();
// MessageBox.Show(" Open database ");
//4: Make a statement sql
// since The database has been opened Can I perform some operations on the database
// Be careful :SQL The string needs to be enclosed in quotation marks
string sql = string.Format("INSERT INTO student (sname,sage) VALUES('{0}', {1})", sname, sage);
// 5: Create an operation sql The object of (MySqlCommand)
MySqlCommand com = new MySqlCommand(sql, con);
// 6: After execution Return a result Integers int
// ExecuteNonQuery: Execute addition, deletion and modification newly added modify Delete
int i= com.ExecuteNonQuery();
if (i > 0) {
// Be similar to js Medium console.log() Prompt box
MessageBox.Show(" Added successfully ");
} else {
MessageBox.Show(" Failure ");
}
}
Tool class ——DBhelp encapsulation
private static String connStr = "server=localhost;database=csharp;uid=root;pwd=root;charset=utf8;sslmode=none";
// Statement link
public static MySqlConnection GetConn()
{
MySqlConnection conn = new MySqlConnection(connStr);//
if (conn.State == ConnectionState.Closed) conn.Open();// Judge whether to turn off Open the link
return conn;// Back to the link
}
public static void CloseAll(MySqlConnection conn)
{
if (conn == null) return;
if (conn.State == ConnectionState.Open || conn.State == ConnectionState.Connecting)
// Judge
conn.Close();// Close links
}
public static int ExecuteNonQuery(string sql) // Additions and deletions encapsulation Returns the affected row
{
MySqlConnection conn = null;
int result; // Set a return value in advance
try
{
conn = GetConn();// For a link
MySqlCommand cmd = new MySqlCommand(sql, conn);
result = cmd.ExecuteNonQuery();// perform sql And return the number of affected rows
}
finally
{
CloseAll(conn);
}
return result;
}
public static MySqlDataReader executeQuery(string sql) // Inquire about
{
MySqlDataReader res = null;
MySqlConnection conn = null;
try
{
MySqlConnection conn1 = GetConn();
MySqlCommand cmd = new MySqlCommand(sql, conn1);
res = cmd.ExecuteReader();
}
finally
{
CloseAll(conn);
}
return res;
}
Optimize new data ( Through tool class )
private void button1_Click(object sender, EventArgs e)
{
string sname = this.sname.Text;
string sage = this.sage.Text;
string sql = string.Format("INSERT INTO student (sname,sage) VALUES('{0}', {1})", sname, sage);
int i = DBhelp.ExecuteNonQuery(sql);
if (i > 0) {
MessageBox.Show(" Added successfully ");
} else {
MessageBox.Show(" Failure ");
}
}
Two 、 Multi meter operation
1: Why do I perform multi table operations
As shown in the figure : When I do class operations , There is no way to operate at this time , Monday 、 They dropped out of school on Wednesday , that 2020 This class no longer exists . Unable to operate class 2020.

2: Solution ( Create an association table , Operating multi table data )

3: Operational data

In general, multi table operations only use query operations
Multi meter operation :as( names ) There is a problem at this time Students without classes ( namely gid by NULL) Don't Don't deserve to be inquired ?SELECT * FROM student AS a, grade AS b WHERE a.gid = b.gid
Advanced multi table query :INNER JOIN Internal connection LEFT JOIN Left connection ( Query with the left table as the main table If the right table has no matching data, use null Instead of )SELECT * FROM student a LEFT JOIN grade b ON a.gid = b.gid
3、 ... and 、 Login operation
// Reset button : Clear the value in the input box
this.textBox1.Text = "";
this.textBox2.Text = "";
this.radioButton1.Checked = true;
this.radioButton2.Checked = false;
// Click login
string password = null;
if (radioButton1.Checked == true)
{
// string.Format Formatted string
string sql = string.Format(@"SELECT password FROM student WHERE username='{0}'", textBox1.Text);
// perform sql Return a result set
MySqlDataReader res = DBhelp.executeQuery(sql);
// Row by row Read on
while (res.Read())
{
password = res["password"].ToString();
}
if (password.Equals(textBox2.Text))
{
MessageBox.Show(" Login successful ");
} else
{
MessageBox.Show(" Wrong account password ");
}
} else
{
string sql = string.Format(@"SELECT password FROM teacher WHERE username='{0}'", textBox1.Text);
MySqlDataReader res = DBhelp.executeQuery(sql);
while (res.Read())
{
password = res["password"].ToString();
}
if (password.Equals(textBox2.Text))
{
MessageBox.Show(" Login successful ");
}
else
{
MessageBox.Show(" Account password failed ");
}
}
Four : Menu operation
1: Show menu

// establish Examples of student menus
StudentMenu stu = new StudentMenu();
// This is the display window
stu.Show();
// After showing the form , Close the previous open window
this.Hide();
2:ListView Use of control
Select the edit line 

modify ListView Box properties 


5、 ... and : Echo data


string gid = null; // Class number
StuList s = null; // If it has been opened, it will no longer new 了
private void AddStudent_Load(object sender, EventArgs e)
{
string sql = string.Format(@"SELECT * FROM grade");
MySqlDataReader res = DBhelp.executeQuery(sql);
while (res.Read())
{
string gname = res["gname"].ToString();
this.comboBox1.Items.Add(gname);
}
// Set the initial value of the drop-down box
comboBox1.Items.Insert(0, " Please select ");
this.comboBox1.SelectedIndex = 0;
}
private void button2_Click(object sender, EventArgs e)
{
string sql = string.Format(@"insert into student (sname, sage, gid, username) values('{0}', {1}, {2}, '{3}')", textBox1.Text, textBox2.Text, gid, textBox4.Text);
int i = DBhelp.ExecuteNonQuery(sql);
if (i > 0)
{
if (s == null)
{
s = new StuList();
s.Show();
}
else
{
s.Reload();
}
DialogResult dialogResult = MessageBox.Show(" Added successfully , Do you want to continue adding ", " New tips ", MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation);
if (dialogResult == DialogResult.Yes)
{
this.TopMost = true;
}
else if (dialogResult == DialogResult.No)
{
this.Hide();
}
} else
{
MessageBox.Show(" Add failed ");
}
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
// obtain gid
string sql1 = string.Format(@"SELECT * FROM grade where gname = '{0}'", comboBox1.Text);
MySqlDataReader res1 = DBhelp.executeQuery(sql1);
while (res1.Read())
{
gid = res1["gid"].ToString();
}
}
6、 ... and 、 Modify delete data

Double click the event in the diagram :
private void listView1_SelectedIndexChanged(object sender, EventArgs e)
{
// Judge whether there is selected data , Echo data when selected
if (this.listView1.SelectedItems.Count > 0)
{
// Get the selected data Index value from 0 Start : Because one row at a time , All index values are 0
ListViewItem lis = this.listView1.SelectedItems[0];
string sid = lis.Tag.ToString();
string sname = lis.Text;
// Get the submenu
string sage = lis.SubItems[1].Text;
string gname = lis.SubItems[2].Text;
string username = lis.SubItems[3].Text;
// Assign the obtained data to the modification box
textBox1.Text = sname;
textBox2.Text = sage;
textBox3.Text = gname;
textBox4.Text = username;
}
}
7、 ... and 、 Value transfer between pages


边栏推荐
- 云图说|每个成功的业务系统都离不开APIG的保驾护航
- 直播预告 | 解构OLAP!新型多维分析架构范式全公开!Apache Doris 将带来五个重磅议题!
- 姿态估计之2D人体姿态估计 - Distribution Aware Coordinate Representation for Human Pose Estimation【转-修改】
- 2D pose estimation for pose estimation - (openpose) realtime multi person 2D pose estimation using part affinity fields
- 剑指 Offer 06. 从尾到头打印链表
- Interpretation of cube technology | past and present life of cube Rendering Design
- 点击解锁广和通5G模组“关键词”
- 竟然還有人說ArrayList是2倍擴容,今天帶你手撕ArrayList源碼
- Quelqu'un a même dit que ArrayList était deux fois plus grand. Aujourd'hui, je vais vous montrer le code source ArrayList.
- VINS理論與代碼詳解4——初始化
猜你喜欢

2D human posture estimation for posture estimation - simple baseline (SBL)

2D human pose estimation for pose estimation - simdr: is 2D Heatmap representation even necessity for human pose estimation?

Vins Theory and Code detail 4 - Initialization

安霸CV2FS/CV22FS获得ASIL C芯片功能安全认证,超越市场同类芯片水平

数字化管理中台+低代码,JNPF开启企业数字化转型的新引擎

Rk3308-- firmware compilation

ORB_ Slam2 visual inertial tight coupling positioning technology route and code explanation 3 - tight coupling optimization model

Implementation of word count case code in MapReduce

2D human posture estimation for posture estimation - numerical coordinate progression with revolutionary neural networks (dsnt)

uniapp中常用到的方法(部分) - 時間戳問題及富文本解析圖片問題
随机推荐
排序与分页
Kubernetes binary installation (v1.20.16) (V) verifying master deployment
Rk3308-- firmware compilation
数字化管理中台+低代码,JNPF开启企业数字化转型的新引擎
CAP 6.1 版本发布通告
从“初代播种”到“落地生花”,广和通在5G商用三年间做了什么?
MapReduce之分区案例的代码实现
姿态估计之2D人体姿态估计 - Simple Baseline(SBL)
Vins theory and code explanation 4 - initialization
Baidu open source ice-ba installation and operation summary
The ultimate buff of smart grid - guanghetong module runs through the whole process of "generation, transmission, transformation, distribution and utilization"
【历史上的今天】6 月 10 日:Apple II 问世;微软收购 GECAD;发明“软件工程”一词的科技先驱出生
Rk3308 key and LED light
MySQL8安装详细步骤
this和对象原型
Unified certification center oauth2 certification pit
Anba cv2fs/cv22fs obtained ASIL C chip function safety certification, surpassing the level of similar chips in the market
MapReduce案例之聚合求和
Méthodes couramment utilisées dans uniapp - TIMESTAMP et Rich Text Analysis picture
直播预告 | 解构OLAP!新型多维分析架构范式全公开!Apache Doris 将带来五个重磅议题!