1.打开Microsoft Visual Studio,点击文件,新建项目,选择C#窗体应用程序
2.将Form1重命名为StuManager,更改窗体StuManager的Text属性为学生信息
3.在工具箱选择工具LayoutControl,放至窗体中(ps:按住鼠标左键,拉动鼠标将控件框住,点击左上角方向标可移动控件位置),接着在工具箱选择控件TextEdit,添加至窗体中(ps:根据实际修改控件的Name属性),根据所需的TextEdit控件数量进行添加,最后添加控件SimpleButton(ps:注意修改控件的Name属性)
4.双击submit按钮,在Click事件中添加代码,整体代码如下:
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;
using System.Data.SqlClient;
using System.Text.RegularExpressions;
namespace StuManager
{
public partial class StuManager : Form
{
public StuManager()
{
InitializeComponent();
}
private void btnSubmit_Click(object sender, EventArgs e)
{
//明确数据库在哪儿:包括服务器、数据库的名字、用户的名字及密码
string connString = "server=.;database=数据库名字;user id = 用户名;password=密码";
//SQL连接上connString
SqlConnection conn = new SqlConnection(connString);
//打开数据库连接
conn.Open();
//SqlDataAdapter是 DataSet和 SQL Server之间的桥接器,用于检索和保存数据
SqlDataAdapter sqlDa = new SqlDataAdapter("select * from tb_Stu", conn);
// DataTable表示内存中数据的一个表
DataTable dt = new DataTable();
//使用SqlDataAdapter的Fill方法(填充),调用select命令
sqlDa.Fill(dt);
//select :选取表 tb_Stu中的第一行的id属性的值
MessageBox.Show(dt.Rows[0]["id"].ToString());
//update 更新表 tb_Stu中的数据-更新id='201631061108'对应的name为'sweet'
string updateStr = "update tb_Stu set name='sweet' where id='201631061108'";
SqlCommand comUpdate = new SqlCommand(updateStr,conn);
int resultUpdate = comUpdate.ExecuteNonQuery();
MessageBox.Show("The total update number is : " + resultUpdate.ToString());
//delete 删除表 tb_Stu中的数据-id='201631061104'所在行
string deleteStr = "delete from tb_Stu where id='201631061104'";
SqlCommand comDelete = new SqlCommand(deleteStr,conn);
int resultDelete = comDelete.ExecuteNonQuery();
MessageBox.Show("The total delete number is : "+resultDelete.ToString());
//insert 根据文本输入框中内容进行数据输入,并验证txtID(长度为12且需输入数字)
string str = txtID.Text;
Regex r = new Regex("^[0-9]*$");
Match m = r.Match(str);
if (!m.Success)
{
MessageBox.Show("Please input numbers!");
}
else
{
//其中txtID、 txtName、txtAge、txtPWD均为对应TextEdit控件的Name
string insertStr = "insert into tb_Stu values('" + txtID.Text + "','" + txtName.Text + "','" + txtAge.Text + "','" + txtPWD.Text + "')";
SqlCommand cmdInsert = new SqlCommand(insertStr, conn);
int resultInsert = cmdInsert.ExecuteNonQuery();
MessageBox.Show("The total insert number is : " + resultInsert.ToString());
}
//关闭数据库连接
conn.Close();
}
}
}