题目:(C#)使用封装好的数据库操作类来实现对数据库的增删查改
数据库信息收集界面:
主界面如下所示:
提示:
①第一个数据库信息收集界面的作用是:使代码的可移植性变强(该界面使用文件操作 ,将数据库服务器名,数据库名,登陆名,密码等信息保存在一个txt文件中;然后在数据库操作类中将文件中的数据库信息读取并组成数据库连接字符串;这样使得当将代码从一个电脑拷贝到另一个电脑时,不需要改动源代码就可以运行,而不会报错)。第二个界面则是对数据库中的数据进行增删查改操作
②在往数据库中添加数据时,使用了正则表达式来防止非法数据;在数据添加时,若数据为空,则会有相应的提示信息(在此使用了异常处理 (try-catch));在使用数据查询时,可以实现多条件的查询,查询的条件为:学号、性别、宿舍号;以及动态的往数据库中插入在文本框输入的数据(例如:
insert into student values('" + textBox1.Text + "','" + textBox2.Text + "','" + comboBox1.Text + "','" + textBox4.Text + "','" + textBox5.Text + "')
)。
Form1.cs
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.IO;
namespace WindowsFormsApplication9
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void btn_OK_Click(object sender, EventArgs e)
{
string path = @"数据库连接信息.txt"; //文件所在路径(使用了相对路径)
string s1, s2, s3, s4; //使用字符串用来保存comboBox中的信息
s1 = comboBox1.Text;
s2 = comboBox2.Text;
s3 = comboBox3.Text;
s4 = comboBox4.Text;
StreamWriter sw = new StreamWriter(path, false);//(文件所在路径,bool值)true表示追加,不覆盖之前的信息
//如果此值为false,则创建一个新文件,如果存在原文件,则覆盖。
//如果此值为true,则打开文件保留原来数据,如果找不到文件,则创建新文件。
sw.WriteLine(s1); //往文件中写入数据库服务器名
sw.WriteLine(s2); //往文件中写入数据库名
sw.WriteLine(s3); //往文件中写入数据库登录名
sw.WriteLine(s4); //往文件中写入与数据库登录名相匹配的密码
sw.Close(); //关闭流。若不关闭,则会抛出异常
Form2 f2 = new Form2();
f2.Show(); //打开Form2窗口
}
private void Form1_Load(object sender, EventArgs e)
{
//添加下拉列表框的选项,使输入操作变的更加方便
comboBox1.Items.Add("本机服务器名");
comboBox2.Items.Add("数据库名");
comboBox3.Items.Add("登录名");
comboBox4.Items.Add("密码");
}
}
}
Form2.cs
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.Text.RegularExpressions; //正则表达式
using System.Data.