【XX系统开发】之PC端【C#上位机】开发过程【01】

一、装VS2019

下载地址:

https://visualstudio.microsoft.com/zh-hans/downloads/

二、装SQLServer2019与SSMS

下载地址如下(百度一下也有):

SQLServer2019:

https://www.microsoft.com/en-us/sql-server/sql-server-2019

SSMS(装完上面的SQLServer2019会有链接):

https://docs.microsoft.com/zh-cn/sql/ssms/download-sql-server-management-studio-ssms?view=sql-server-ver15

三、编写测试代码,连接SQL Server数据库

在SQL Server通过如下代码新建了数据库和表

--指向要操作的数据库
use master
go
--创建数据库
create database OrderSystemDB
on primary
(
	--数据库的逻辑文件名,必须唯一
	name='OrderSystemDB_data',
	--数据库物理文件名(绝对路径)
	filename='D:\DB\OrderSystemDB_data.mdf',--主数据文件名
	--数据库初始文件大小
	size=10MB,
	--数据文件增值量
	filegrowth=1MB
)
,
(
	name='OrderSystemDB_data1',
	filename='D:\DB\OrderSystemDB_data.ndf',--次要数据文件名
	size=10MB,
	filegrowth=1MB

)
log on
(
	name='OrderSystemDB_log',
	filename='D:\DB\OrderSystemDB_log.ldf',--日志文件名
	size=10MB,
	filegrowth=1MB

)
go
--指向要操作的数据库
use OrderSystemDB
go
--菜式信息表
if exists(select * from sysobjects where name='CaiShiInfo')
drop table CaiShiInfo
go
create table CaiShiInfo
(
	CaiShiId int identity(1000,1) primary key,--菜式编号,主键
	CaiShiName nvarchar(25) not null,--菜式名
	CaiShiPrice decimal(10,2) not null,--菜式价格
)
go
--指向要操作的数据库
use OrderSystemDB
go
--进货信息表
if exists(select * from sysobjects where name='JinHuoInfo')
drop table JinHuoInfo
go
create table JinHuoInfo
(
	JinHuoId int identity(1000,1) primary key,--进货编号,主键
	JinHuoTime varchar(30) not null,--进货时间
	JinHuoGoodsName nvarchar(25) not null,--进货商品名
	JinHuoGoodsQuantity int not null,--进货商品数量
	JinHuoGoodsPrice decimal(10,2) not null,--进货商品价格
)
go
--指向要操作的数据库
use OrderSystemDB
go
--用户信息表
if exists(select * from sysobjects where name='Login')
drop table Login
go
create table Login
(
	LoginId int identity(1000,1) primary key,--用户编号,主键
	LoginName nvarchar(25) not null,--用户名
	LoginPassword varchar(20) check(len(LoginPassword)>=6 and len(LoginPassword)<=20) not null,--用户密码
	LoginPermission int not null,--用户权限
)
go
--指向要操作的数据库
use OrderSystemDB
go
--账单信息表
if exists(select * from sysobjects where name='Bill')
drop table Bill
go
create table Bill
(
	BillId int identity(100000,1) primary key,--账单编号,主键
	TableNum int not null,--桌号
	OrderName varchar(20) not null,--菜名
	OrderQuantity int not null,--数量
	Consume decimal(12,2) not null,--消费
)
go
--指向要操作的数据库
use OrderSystemDB
go
--商品信息表
if exists(select * from sysobjects where name='GoodsInfo')
drop table GoodsInfo
go
create table GoodsInfo
(
	GoodsId int identity(1000,1) primary key,--商品编号,主键
	GoodsName nvarchar(25) not null,--商品名
	GoodsPrice decimal(10,2) not null,--商品价格
)
go
--指向要操作的数据库
use OrderSystemDB
go
--收入信息表
if exists(select * from sysobjects where name='IncomeInfo')
drop table IncomeInfo
go
create table IncomeInfo
(
	IncomeId int identity(100000,1) primary key,--收入编号,主键
	DailyIncome decimal(12,2) not null,--每日收入总额
	IncomeDate varchar(30) not null,--日期
)
go
--指向要操作的数据库
use OrderSystemDB
go
--餐桌使用情况信息表
if exists(select * from sysobjects where name='TableUsed')
drop table TableUsed
go
create table TableUsed
(
	TableId int identity(1000,1) primary key,--桌子编号,主键
	TableState int not null,--桌子使用情况,“0”表示空闲,“1”表示使用中
)
go
--指向要操作的数据库
use OrderSystemDB
go
--添加测试数据
--insert into Login(LoginId,LoginName,LoginPassword,LoginPermission)
--values(0001,'admin','111111',1),
--(0002,'boss','123456',2),
--(0003,'worker','123456',3)

--添加测试数据
insert into Login(LoginName,LoginPassword,LoginPermission)
values('admin','111111',1),
('boss','123456',2),
('worker','123456',3)

--测试:查询
select * from Login
select Count(*) as LoginId from Login
select LoginPassword from Login where LoginId = 1002

--测试:删除
delete from Login where LoginId=1003

--测试:修改
update Login set LoginPassword='666666' where LoginId=1001

 然后在VS2019的C#工程中,添加引用:System.Configuration

并更改App.config为:

(其中数据库的名字OrderSystemDB,登录的账号sa和密码139***mm,都需根据自己的数据库进行更改)

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <startup> 
        <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.7.2" />
    </startup>
  <connectionStrings>
    <add name="connString" connectionString="Server = .;DataBase = OrderSystemDB;Uid = sa; Pwd = 139***mm"/>
  </connectionStrings>
  
</configuration>

然后新建了如下的类:

注意:下文中的“connString”应与上文的name = “connString”保持一致。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Configuration;
using System.Data.SqlClient;

namespace OrderSystem
{
    class SQLHelper
    {
        private static string connString = ConfigurationManager.ConnectionStrings["connString"].ToString();

        /// <summary>
        /// 执行增删改操作的方法
        /// </summary>
        /// <param name="sql"></param>
        /// <returns></returns>
        public static int Update(string sql)
        {
            //【1】创建连接对象
            SqlConnection conn = new SqlConnection(connString);
            //【2】创建Command对象
            SqlCommand cmd = new SqlCommand(sql, conn);

            try
            {
                //【3】打开数据库连接
                conn.Open();
                //【4】执行操作(下面的方法,只能用于执行insert、update、delete操作,不能执行select)
                return cmd.ExecuteNonQuery();
            }
            catch(Exception ex)
            {
                throw new Exception("执行方法public static int Update(string sql)发生异常" + ex.Message);
            }
            finally
            {
                //【5】关闭连接
                conn.Close();
            }
        }

        /// <summary>
        /// 执行单一结果返回的查询方法
        /// </summary>
        /// <param name="sql"></param>
        /// <returns></returns>
        public static object GetSingleResult(string sql)
        {
            //【1】创建连接对象
            SqlConnection conn = new SqlConnection(connString);
            //【2】创建Command对象
            SqlCommand cmd = new SqlCommand(sql, conn);

            try
            {
                //【3】打开数据库连接
                conn.Open();
                //【4】执行操作(下面的方法,只能用于执行insert、update、delete操作,不能执行select)
                return cmd.ExecuteScalar();
            }
            catch (Exception ex)
            {
                throw new Exception("执行方法public static object GetSingleResult(string sql)发生异常" + ex.Message);
            }
            finally
            {
                //【5】关闭连接
                conn.Close();
            }
        }

        /// <summary>
        /// 执行结果集的查询
        /// </summary>
        /// <param name="sql"></param>
        /// <returns></returns>
        public static SqlDataReader GetReader(string sql)
        {
            SqlConnection conn = new SqlConnection(connString);
            SqlCommand cmd = new SqlCommand(sql, conn);
            try
            {
                conn.Open();
                //添加枚举CommandBehavior.CloseConnection后,将来reader对象的连接会跟随reader对象的关闭自动关闭
                return cmd.ExecuteReader(System.Data.CommandBehavior.CloseConnection);
            }
            catch (Exception ex)
            {
                throw new Exception("执行方法public static SqlDataReader GetReader(string sql)发生异常" + ex.Message);
            }
            //finally //本方法中不可直接把连接关闭,否则出错
            //{
            //    conn.Close();
            //}
        }
    }
}

 然后再在VS2019的C#工程中,新建了如下的类,用于测试程序与数据库的连接:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.Data;

namespace OrderSystem
{
    static class Program
    {
        /// <summary>
        /// 应用程序的主入口点。
        /// </summary>
        [STAThread]
        static void Main()
        {
            //ConnectDB();
            //ExecuteInsert();
            //ExecuteUpdate();
            //ExecuteDelete();
            //ExecuteSingleResult();
            //ExecuteReader();
            //ExecuteInsertByHelper();
            //ExecuteSingleResultByHelper();
            //ExecuteReaderByHelper();

            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new Form1());
            //Console.Read();
        }

        static void ConnectDB()
        {
            string connString = "Server = .;DataBase = OrderSystemDB;Uid = sa; Pwd = 139***mm";
            SqlConnection conn = new SqlConnection(connString);

            Console.WriteLine("start");
            //打开连接
            conn.Open();
            if(conn.State == ConnectionState.Open)
            {
                Console.WriteLine("连接成功!");
            }

            //关闭连接
            conn.Close();
            if(conn.State == ConnectionState.Closed)
            {
                Console.WriteLine("关闭成功");
            }
        }

        static void ExecuteInsert()
        {
            //【1】创建连接对象
            string connString = "Server = .;DataBase = OrderSystemDB;Uid = sa; Pwd = 139***mm";
            SqlConnection conn = new SqlConnection(connString);

            //定义sql语句
            string sql = "insert into Login(LoginName,LoginPassword,LoginPermission)";
            sql += "values('worker','123456',3)";

            //【2】创建Command对象
            SqlCommand cmd = new SqlCommand(sql,conn);

            //【3】打开数据库连接
            conn.Open();

            //【4】执行操作(下面的方法,只能用于执行insert、update、delete操作,不能执行select)
            int result = cmd.ExecuteNonQuery();

            Console.WriteLine("受影响的行数="  + result);

            //【5】关闭连接
            conn.Close();
        }

        static void ExecuteUpdate()
        {
            //【1】创建连接对象
            string connString = "Server = .;DataBase = OrderSystemDB;Uid = sa; Pwd = 139***mm";
            SqlConnection conn = new SqlConnection(connString);

            //定义sql语句
            string sql = "update Login set LoginPassword='1234567' ";
            sql += "where LoginId=1003";

            //【2】创建Command对象
            SqlCommand cmd = new SqlCommand(sql, conn);

            //【3】打开数据库连接
            conn.Open();

            //【4】执行操作(下面的方法,只能用于执行insert、update、delete操作,不能执行select)
            int result = cmd.ExecuteNonQuery();

            Console.WriteLine("受影响的行数=" + result);

            //【5】关闭连接
            conn.Close();
        }

        static void ExecuteDelete()
        {
            //【1】创建连接对象
            string connString = "Server = .;DataBase = OrderSystemDB;Uid = sa; Pwd = 139***mm";
            SqlConnection conn = new SqlConnection(connString);

            //定义sql语句
            string sql = "delete from Login ";
            sql += "where LoginId=1003";

            //【2】创建Command对象
            SqlCommand cmd = new SqlCommand(sql, conn);

            //【3】打开数据库连接
            conn.Open();

            //【4】执行操作(下面的方法,只能用于执行insert、update、delete操作,不能执行select)
            int result = cmd.ExecuteNonQuery();

            Console.WriteLine("受影响的行数=" + result);

            //【5】关闭连接
            conn.Close();
        }

        static void ExecuteSingleResult()
        {
            //【1】创建连接对象
            string connString = "Server = .;DataBase = OrderSystemDB;Uid = sa; Pwd = 139***mm";
            SqlConnection conn = new SqlConnection(connString);

            //定义sql语句
            string sql = "select Count(*) as LoginId from Login";

            //【2】创建Command对象
            SqlCommand cmd = new SqlCommand(sql, conn);

            //【3】打开数据库连接
            conn.Open();

            //【4】执行查询(下面的方法一般用于查询)
            object result = cmd.ExecuteScalar();

            Console.WriteLine("查询结果=" + result);

            //【5】关闭连接
            conn.Close();
        }

        static void ExecuteReader()
        {
            //【1】创建连接对象
            string connString = "Server = .;DataBase = OrderSystemDB;Uid = sa; Pwd = 139***mm";
            SqlConnection conn = new SqlConnection(connString);

            //定义sql语句
            string sql = "select LoginName,LoginPassword from Login where LoginId < 1002";

            //【2】创建Command对象
            SqlCommand cmd = new SqlCommand(sql, conn);

            //【3】打开数据库连接
            conn.Open();

            //【4】执行查询
            SqlDataReader reader = cmd.ExecuteReader();

            //判断是否有查询结果,从而决定读取数据
            while(reader.Read())
            {
                Console.WriteLine($"{reader["LoginName"]}\t{reader["LoginPassword"]}");
            }
            reader.Close();//关闭读取器对象

            //【5】关闭连接
            conn.Close();
        }

        static void ExecuteInsertByHelper()
        {
            string sql = "insert into Login(LoginName,LoginPassword,LoginPermission)";
            sql += "values('worker2','1234567',3)";

            int result = SQLHelper.Update(sql);
            Console.WriteLine(result);
        }

        static void ExecuteSingleResultByHelper()
        {
            string sql = "select Count(*) as LoginId from Login";
            object result = SQLHelper.GetSingleResult(sql);
            Console.WriteLine(result);
        }

        static void ExecuteReaderByHelper()
        {
            //定义sql语句
            string sql = "select LoginName,LoginPassword from Login where LoginId < 1002";

            //执行查询
            SqlDataReader reader = SQLHelper.GetReader(sql);

            //判断是否有查询结果,从而决定读取数据
            while (reader.Read())
            {
                Console.WriteLine($"{reader["LoginName"]}\t{reader["LoginPassword"]}");
            }
            reader.Close();//关闭读取器对象
        }
    }
}

至此,测试完成。

发布了32 篇原创文章 · 获赞 18 · 访问量 6534

猜你喜欢

转载自blog.csdn.net/mm13420109325/article/details/105019253
今日推荐