使用封装好的数据库操作类来实现对数据库的增删查改

题目:(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.SqlClient;

namespace WindowsFormsApplication9
{
    public partial class Form2 : Form
    {
        public Form2()
        {
            InitializeComponent();
        }
        static string str1 = "select * from student";
        private void Form2_Load(object sender, EventArgs e)
        {
            iBaby.DBOperation.BindDB(dataGridView1, str1, "student");//调用DBOperation中的方法将信息绑定到DataGridView
            comboBox1.Items.Add("男");
            comboBox1.Items.Add("女");
            //this.BackgroundImage = System.Drawing.Image.FromFile("1.png");//使用了相对路径
            //添加背景图片,并设置窗体的BackGroundImageLayout属性为Stretch(背景图片拉申),让图片大小随着窗体大小改变而改变
        }

        private void btn_add_Click_1(object sender, EventArgs e)
        {
            string str2 = "insert into student values('" + textBox1.Text + "','" + textBox2.Text + "','" + comboBox1.Text + "','" + textBox4.Text + "','" + textBox5.Text + "')";
            string str2_1 = "select *  from student where 学号='" + textBox1.Text + "'";
            SqlDataReader read = iBaby.DBOperation.getReader(str2_1);
            if (read.Read())     //读取数据库,判断学号是否重复
            {
                MessageBox.Show("该数据已存在,请勿重复插入!");
            }
            else
            {
                try
                {
                    if (textBox1.Text == "" || textBox2.Text == "" || comboBox1.Text == "" || textBox4.Text == "" || textBox5.Text == "")
                    {
                        throw new ArgumentNullException();//参数为空
                    }
                    else
                    {
                        //使用正则表达式来防止非法数据
                        Regex reg1 = new Regex("^161210\\d{3}$");
                        Regex reg2 = new Regex("^1\\d{10}$");
                        Regex reg3 = new Regex("^\\d{4,5}$");
                        //Regex类的IsMatch()方法返回一个bool值,如果有匹配项,返回true,否则返回false
                        if (!reg1.IsMatch(textBox1.Text))
                        {
                            MessageBox.Show("输入的学号格式有误,请重新输入!");
                        }
                        else if (!reg2.IsMatch(textBox4.Text))
                        {
                            MessageBox.Show("输入的联系方式格式有误,请重新输入!");
                        }
                        else if (!reg3.IsMatch(textBox5.Text))
                        {
                            MessageBox.Show("输入的宿舍号格式有误,请重新输入!");
                        }
                        else
                        {
                            iBaby.DBOperation.exesql(str2);
                            //调用DBOperation中的方法将数据插入到数据库
                            //iBaby.DBOperation.GetDataTable(str1);//清除控件上的信息
                            iBaby.DBOperation.BindDB(dataGridView1, str1, "student");
                            //将插入数据后的新表重新绑定到DataGridView控件中,显示新表
                            MessageBox.Show("数据添加成功!");
                        }
                    }
                }
                catch (ArgumentNullException e1)
                {
                    MessageBox.Show(e1.Message + "\n(每个值都必须输入才能添加)");
                    //因为直接用e1.Message获取到的“信息异常提示”都是一样的,为了区分,所以在后面加了语句。
                }
            }
        }

        private void btn_del_Click_1(object sender, EventArgs e)
        {
            string str3 = "delete from student where 学号='" + textBox1.Text + "'";
            try
            {
                if (textBox1.Text == "")
                {
                    throw new ArgumentNullException();//参数为空
                }
                else
                {
                    Regex reg1 = new Regex("^161210\\d{3}$");
                    if (!reg1.IsMatch(textBox1.Text))
                    {
                        MessageBox.Show("输入的学号格式有误,请重新输入!");
                    }
                    else
                    {
                        iBaby.DBOperation.exesql(str3);
                        //调用DBOperation中的方法将数据库中指定的数据删除
                        // iBaby.DBOperation.GetDataTable(str1);//清除控件上的信息
                        iBaby.DBOperation.BindDB(dataGridView1, str1, "student");
                        //将删除数据后的新表重新绑定到DataGridView控件中,显示新表
                        MessageBox.Show("数据删除成功!");
                    }
                }
            }
            catch (ArgumentNullException e1)
            {
                MessageBox.Show(e1.Message + "\n(删除是按照学号来进行的,所以不能为空)");
            }
        }

        private void btn_sel_Click_1(object sender, EventArgs e)
        {
            string str4 = "";
            string str4_1 = "select * from student where 学号='" + textBox1.Text + "'";
            string str4_2 = "select * from student where 性别='" + comboBox1.Text + "'";
            string str4_3 = "select * from student where 住宿号='" + textBox5.Text + "'";
            if (textBox1.Text != "")
            {
                if (str4 == "")
                {
                    str4 = str4_1;
                }
                else
                {
                    str4 = str4 + "AND 学号='" + textBox1.Text + "'";
                }
            }
            if (comboBox1.Text != "")
            {
                if (str4 == "")
                {
                    str4 = str4_2;
                }
                else
                {
                    str4 = str4 + "AND 性别='" + comboBox1.Text + "'";
                }
            }
            if (textBox5.Text != "")
            {
                if (str4 == "")
                {
                    str4 = str4_3;
                }
                else
                {
                    str4 = str4 + "AND 住宿号='" + textBox5.Text + "'";
                }
            }
            try
            {
                if (str4 == "")
                {
                    throw new ArgumentNullException();
                }
                else
                {
                    iBaby.DBOperation.BindDB(dataGridView1, str4, "student");
                }
            }
            catch (ArgumentNullException e1)
            {
                MessageBox.Show(e1.Message + "\n查询条件不能为空!");
            }
        }

        private void btn_mod_Click_1(object sender, EventArgs e)
        {
            string str5_1 = "update student set 姓名='" + textBox2.Text + "' where 学号='" + textBox1.Text + "'";
            string str5_2 = "update student set 性别='" + comboBox1.Text + "' where 学号='" + textBox1.Text + "'";
            string str5_3 = "update student set 联系方式='" + textBox4.Text + "' where 学号='" + textBox1.Text + "'";
            string str5_4 = "update student set 住宿号='" + textBox5.Text + "' where 学号='" + textBox1.Text + "'";
            try
            {
                if (textBox1.Text == "" || textBox2.Text == "" || comboBox1.Text == "" || textBox4.Text == "" || textBox5.Text == "")
                {
                    throw new ArgumentNullException();//参数为空
                }
                else
                {
                    Regex reg1 = new Regex("^161210\\d{3}$");
                    Regex reg2 = new Regex("^1\\d{10}$");
                    Regex reg3 = new Regex("^\\d{4,5}$");
                    if (!reg1.IsMatch(textBox1.Text))
                    {
                        MessageBox.Show("输入的学号格式有误,请重新输入!");
                    }
                    else if (!reg2.IsMatch(textBox4.Text))
                    {
                        MessageBox.Show("输入的联系方式格式有误,请重新输入!");
                    }
                    else if (!reg3.IsMatch(textBox5.Text))
                    {
                        MessageBox.Show("输入的宿舍号格式有误,请重新输入!");
                    }
                    else
                    {
                        iBaby.DBOperation.exesql(str5_1);
                        iBaby.DBOperation.exesql(str5_2);
                        iBaby.DBOperation.exesql(str5_3);
                        iBaby.DBOperation.exesql(str5_4);
                        //调用DBOperation中的方法修改指定学号的学生的信息
                        // iBaby.DBOperation.GetDataTable(str1);//清除控件上的信息
                        iBaby.DBOperation.BindDB(dataGridView1, str1, "student");
                        //将修改后的新表重现绑定到DataGridView控件中,显示新表
                        MessageBox.Show("数据修改成功!");
                    }
                }
            }
            catch (ArgumentNullException e1)
            {
                MessageBox.Show(e1.Message + "\n(若想要修改则必须修改全部信息,才能完成修改!)\n(或者学号为空,无法查询到相应的数据,并对其进行修改!)");
            }
        }
    }
}

(数据库操作类)DBOperation.cs

using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.IO;// Directory


namespace iBaby
{
    class DBOperation
    {
       // static String currentdir = Directory.GetCurrentDirectory();
        //static String constr = @"Data Source=.\SQLEXPRESS;AttachDbFilename=" + currentdir + @"\susheguanli_data.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True";
        //static String constr = @"Data Source=.\SQLEXPRES;AttachDbFilename="+currentdir+@"\Data\iBaby_Data.MDF;Integrated Security=True;Connect Timeout=30;User Instance=True";
        //static String constr = @"Data Source=(local)\MSSQLSERVERR;Initial Catalog=sa_test1;User ID=sa;password=123;";
        public static string A()  //方法必须声明为static的,否则下面的constr无法直接调用
        {
            string path = @"数据库连接信息.txt";
            string[] content = File.ReadAllLines(path, Encoding.Default);//使用string数组来存储从文件中读取到的信息
            //读取path路径下的文件内容,若不加“Encoding.Default”则会中文乱码
            //Encoding.Default(编码.默认)(C#中的默认编码方式为Unicode)(记事本的默认编码方式为ANSI)
            string constr1 = @"Data Source='" + content[0] + "';Initial Catalog='" + content[1] + "';User ID='" + content[2] + "';password='" + content[3] + "';";
            return constr1;
        }
        static String constr = A();  //静态方法可以直接用类.函数调用,不需要再声明对象来调用(在本类中可以直接使用方法名调用)
        //绑定DataGridView
        public static void BindDB(DataGridView dg,string strSql, string Tname)
        {
            SqlConnection con = new SqlConnection(constr);
            SqlDataAdapter sda = new SqlDataAdapter(strSql, con);
            DataSet ds = new DataSet();
            sda.Fill(ds, Tname);
            dg.DataSource = ds.Tables[Tname];
        }
        //  获取数据表
        public static DataTable  GetDataTable( string strSql)
        {
            DataTable dt ;
            SqlConnection con = new SqlConnection(constr);
            SqlDataAdapter sda = new SqlDataAdapter(strSql, con);
            DataSet ds = new DataSet();
            sda.Fill(ds, "DataTab");
            dt = ds.Tables["DataTab"];
            //dt.Clear();  //清除控件上的内容
            return dt;
        }
       ///添加 删除 修改
        public static void exesql(String strsql)  
        {
            SqlConnection con = new SqlConnection(constr);
            con.Open();///建立连接
            SqlCommand cmd = con.CreateCommand();
            cmd.CommandText = strsql;
            cmd.ExecuteNonQuery();
            con.Close();
        }
        //根据select查询sql,返回datareader
        public static SqlDataReader getReader(string sql)
       {
            SqlConnection con = new SqlConnection(constr);
            SqlCommand cmd = new SqlCommand(sql, con);
            con.Open();
            SqlDataReader reader = cmd.ExecuteReader();
            return reader;
       }
       
    }
}


猜你喜欢

转载自blog.csdn.net/jiuying684/article/details/80470756
今日推荐