C#数据库的使用

使用背景:最近做网络应用编程的期末实验,很抽风地做了一个什么图书馆管理系统。。。听人说,出去实习找工作千万千万不要说你做过图书馆管理系统,因为它不仅不能给你加分,反而还会扣分。。也是呵呵了,已经做成差不多了,又是期末实在不想改,拿别人的过来终究觉得心里愧疚。。。(况且老师提问里面的关键代码怎么办?好尴尬)额,这是本博客的写作背景,不喜欢的可以忽略了。
简要介绍一下我们的系统(主要是数据库方面的)
数据库我们采用的是VS2015自带的SQL Sever,其实VS可以采用数据库模型的方式,使用数据库实例之类的方式直接对数据库操作,(貌似很方便?)但是我们没有这样,我们采用的是通过连接字符串,编写专门的操作数据库类(里面写有多个操作数据库数据的方法),这种方法其实是在项目开发中比较常用的数据库方法,Java项目也都是这样用的,所以我把关键的记下了,以备不时之需。

先提前说一下关于数据库中表的命名。本来表名其实是应该比较随意的,但实际上有一个很重要的问题,就是避开SQL Sever中的关键字。比如admin,user,如果你很不幸把表名设置成关键字,那么sql语句再写怎么正确,还是会报错的。报错信息为:错误:Incorrect syntax near the keyword ‘user’,uer是保留字,改为[user]即可,不过方便起见,建议用其他的单词代替。

下面是我的数据库类的部分方法。

using System.Data.SqlClient;
//返回数据库连接
 public SqlConnection ConnectDataBase()
        {
            //设置连接字符串:双击已经连接的mdf文件,在右下角属性可以看到连接字符串,复制粘贴过来即可。
            SqlConnection conn = new SqlConnection(@"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\qingyue\Desktop\Library\bookmanage.mdf;Integrated Security=True;Connect Timeout=30"); 
            return conn;
        }

循环查询和执行

//用户注册方法
 public bool user_register(UserInfo user)
        {
            bool flag;
            try
            {
                SqlConnection conn = ConnectDataBase();
                //打开数据库  
                conn.Open();
                //创建查询语句   
                string sql = "insert into consumer(studentid,username,password,sname,sex,cid,faculty,profession) values(N"
                        + "'" + user.Studentid + "','" + user.Username + "','" + user.Password + "','" + user.Sname + "','" + user.Sex + "','" + user.Cid + "','" + user.Faculty + "','" + user.Profession + "')";
                SqlCommand cmd = new SqlCommand(sql, conn);
                int result = cmd.ExecuteNonQuery();
                conn.Close();
                flag = true;
            }
            catch(SqlException e)
            {
                flag = false;
            }
            return flag;
        }

        //返回用户信息
        public UserInfo user_info(int uid)
        {

            SqlConnection conn = ConnectDataBase();
            //打开数据库  
            UserInfo user = new UserInfo();
            conn.Open();
            SqlCommand querySingleInfo = conn.CreateCommand();
            querySingleInfo.CommandText = "SELECT * FROM consumer";
            SqlDataReader singleInfoReader = querySingleInfo.ExecuteReader();
            //有多行数据,用while循环  
            while (singleInfoReader.Read())
            {
                if (uid==(int)singleInfoReader["uid"])
                {
                    user.Studentid = singleInfoReader["studentid"].ToString();
                    user.Sname = singleInfoReader["sname"].ToString();
                    user.Profession = singleInfoReader["profession"].ToString();
                    user.Cid = (int)singleInfoReader["cid"];
                    user.Faculty = singleInfoReader["faculty"].ToString();
                    user.Sex = (int)singleInfoReader["sex"];
                    return user;
                }

            }
            return user;
        }

特别的一个地方:

//查询所有图书。
 while (singleInfoReader.Read())
            {
                BookInfo bookinfo = new BookInfo();//必须放在这里,这样每次都有一个新的bookinfo对象添加进列表,确保所有对象都加入list,如果放在循环外,最终只能添加一条记录到list里面。
                bookinfo.Booknum = singleInfoReader["booknum"].ToString();
                bookinfo.Bookname = singleInfoReader["bookname"].ToString();
                bookinfo.Author = singleInfoReader["author"].ToString();
                bookinfo.Totlenum = (int)singleInfoReader["totalnum"];
                bookinfo.Publish = singleInfoReader["publish"].ToString();
                bookinfo.Lendnum = (int)singleInfoReader["lendnum"];
                booklist.Add(bookinfo);
            }

另外,在还书(也可能有其他类似的情况),处理借书记录的时候,应该以用户id,图书编号还有借书时间作为删除条件,借书时间这个很必要,因为一个用户可能借到多本相同书名的图书,而借书时间算是一个很唯一的标准(具体到借书的时分秒),所以要注意一下。

using System;using System.Collections.Generic;using System.Text;using System.Data;using System.Data.SqlClient; namespace DatabaseOperate{ class SqlOperateInfo { //Suppose your ServerName is "aa",DatabaseName is "bb",UserName is "cc", Password is "dd" private string sqlConnectionCommand = "Data Source=aa;Initial Catalog=bb;User ID=cc;Pwd=dd"; //This table contains two columns:KeywordID int not null,KeywordName varchar(100) not null private string dataTableName = "Basic_Keyword_Test"; private string storedProcedureName = "Sp_InertToBasic_Keyword_Test"; private string sqlSelectCommand = "Select KeywordID, KeywordName From Basic_Keyword_Test"; //sqlUpdateCommand could contain "insert" , "delete" , "update" operate private string sqlUpdateCommand = "Delete From Basic_Keyword_Test Where KeywordID = 1"; public void UseSqlReader() { SqlConnection sqlConnection = new SqlConnection(sqlConnectionCommand); SqlCommand sqlCommand = new SqlCommand(); sqlCommand.CommandType = System.Data.CommandType.Text; sqlCommand.Connection = sqlConnection; sqlCommand.CommandText = sqlSelectCommand; sqlConnection.Open(); SqlDataReader sqlDataReader = sqlCommand.ExecuteReader(); while(sqlDataReader.Read()) { //Get KeywordID and KeywordName , You can do anything you like. Here I just output them. int keywordid = (int)sqlDataReader[0]; //the same as: int keywordid = (int)sqlDataReader["KeywordID"] string keywordName = (string)sqlDataReader[1]; //the same as: string keywordName = (int)sqlDataReader["KeywordName"] Console.WriteLine("KeywordID = " + keywordid + " , KeywordName = " + keywordName); } sqlDataReader.Close(); sqlCommand.Dispose(); sqlConnection.Close(); } public void UseSqlStoredProcedure() { SqlConnection sqlConnection = new SqlConnection(sqlConnectionCommand); SqlCommand sqlCommand = new SqlCommand(); sqlCommand.CommandType = CommandType.StoredProcedure; sqlCommand.Connection = sqlConnection; sqlCommand.CommandText = storedProcedureName; sqlConnection.Open(); sqlCommand.ExecuteNonQuery(); //you can use reader here,too.as long as you modify the sp and let it like select * from .... sqlCommand.Dispose(); sqlConnection.Close(); } public void UseSqlDataSet() { SqlConnection sqlConnection = new SqlConnection(sqlConnectionCommand); SqlCommand sqlCommand = new SqlCommand(); sqlCommand.CommandType = System.Data.CommandType.Text; sqlCommand.Connection = sqlConnection; sqlCommand.CommandText = sqlSelectCommand; sqlConnection.Open(); SqlDataAdapter sqlDataAdapter = new SqlDataAdapter(); sqlDataAdapter.SelectCommand = sqlCommand; DataSet dataSet = new DataSet(); //sqlCommandBuilder is for update the dataset to database SqlCommandBuilder sqlCommandBuilder = new SqlCommandBuilder(sqlDataAdapter); sqlDataAdapter.Fill(dataSet, dataTableName); //Do something to dataset then you can update it to Database.Here I just add a row DataRow row = dataSet.Tables[0].NewRow(); row[0] = 10000; row[1] = "new row"; dataSet.Tables[0].Rows.Add(row); sqlDataAdapter.Update(dataSet, dataTableName); sqlCommand.Dispose(); sqlDataAdapter.Dispose(); sqlConnection.Close(); } }}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值