C# 学习笔记(19)操作SQL Server下

C# 学习笔记(19)操作SQL Server下

ADO.net操作数据库

这应该是比较老的技术了,以后有空的话学学 Linq

/// 
/// 数据库使用类
/// 
public static class MySqlHelper
{
     
    /// 
    /// 1.数据库连接字符串
    /// 
    public static string conStr;

    /// 
    /// SQL 增 删 改
    /// 
    /// sql命令
    /// sql参数
    /// 
    public static int ExecuteNonQuery(string sql, params SqlParameter[] ps)
    {
     
        try
        {
     
            //2.创建连接对象  using结束后会自动释放资源
            using (SqlConnection conn = new SqlConnection(conStr))
            {
     
                //3.创建执行SQL语句的对象
                SqlCommand cmd = new SqlCommand(sql, conn);

                //4.编写SQL语句
                cmd.Parameters.AddRange(ps);
                cmd.CommandTimeout = 1;

                //5.打开SQL连接
                conn.Open();

                //6.执行SQL语句
                return cmd.ExecuteNonQuery();
            }
        }
        catch (Exception e)
        {
     
            throw e;
        }
    }

    /// 
    /// SQL 查询一行数据
    /// 
    /// 
    /// 
    /// 
    public static object ExecuteScalar(string sql, params SqlParameter[] ps)
    {
     
        try
        {
     
            using (SqlConnection conn = new SqlConnection(conStr))
            {
     
                SqlCommand cmd = new SqlCommand(sql, conn);
                cmd.Parameters.AddRange(ps);
                cmd.CommandTimeout = 1;
                conn.Open();
                return cmd.ExecuteScalar();
            }
        }
        catch (Exception e)
        {
     
            throw e;
        }
    }

    /// 
    /// SQL 查询一块数据,并把数据存放在一个表中
    /// 
    /// 命令
    /// 参数
    /// 内存中的表
    public static DataTable ExecuteTable(string sql, params SqlParameter[] ps)
    {
     
        try
        {
     
            using (SqlConnection conn = new SqlConnection(conStr))
            {
     
                SqlDataAdapter adapter = new SqlDataAdapter(sql, conn);
                adapter.SelectCommand.Parameters.AddRange(ps);
                adapter.SelectCommand.CommandTimeout = 1;
                DataTable dataTable = new DataTable();
                adapter.Fill(dataTable);
                return dataTable;
            }
        }
        catch (Exception e)
        {
     
            throw e;
        }
    }

    /// 
    /// SQL 查询一块数据
    /// 
    /// 
    /// 
    /// 
    public static SqlDataReader ExecuteReader(string sql, params SqlParameter[] ps)
    {
     
        try
        {
     
            SqlConnection conn = new SqlConnection(conStr);
            SqlCommand cmd = new SqlCommand(sql, conn);
            cmd.Parameters.AddRange(ps);
            cmd.CommandTimeout = 1;
            conn.Open();
            return cmd.ExecuteReader(CommandBehavior.CloseConnection);
        }
        catch(Exception e)
        {
     
            throw e;
        }
    }
}

修改存储过程

根据要实现的功能,创建修改对应的存储过程和视图,可以一遍写程序一遍优化存储过程和视图

--创建视图 studentInfoTable
create view studentInfoTable
as
select studentTable.id as 学生编号, studentTable.name as 姓名, genderTable.name as 性别, 
gradeTable.name as 班级,  (provinceTable.province + cityTable.cityName + isNull(studentTable.address, '')) as 家庭地址
from studentTable 
inner join cityTable on cityTable.id = studentTable.cityID   
inner join provinceTable on cityTable.provinceID = provinceTable.id
inner join genderTable on genderTable.id = studentTable.gender
inner join gradeTable on gradeTable.id = studentTable.gradeID
select * from studentInfoTable

C# 学习笔记(19)操作SQL Server下_第1张图片

--创建视图 studentMinuteInfoTable
create view studentMinuteInfoTable
as
select studentTable.id as 学生编号, studentTable.name as 姓名, genderTable.name as 性别, 
gradeTable.name as 班级,  provinceTable.province as,  cityTable.cityName as, studentTable.address as 详细地址
from studentTable 
inner join cityTable on cityTable.id = studentTable.cityID   
inner join provinceTable on cityTable.provinceID = provinceTable.id
inner join genderTable on genderTable.id = studentTable.gender
inner join gradeTable on gradeTable.id = studentTable.gradeID
select * from studentMinuteInfoTable

C# 学习笔记(19)操作SQL Server下_第2张图片

--获取一页学生信息
alter proc GetStudentInfoPage
	@pageIndex int, --要查询的页序号
	@pageSize  int  --页大小
as
begin
	select * from (select ROW_NUMBER() over(order by 学生编号) as 行序号, * from studentInfoTable) as t1 
	where 行序号 between (@pageIndex-1)*@pageSize+1 and @pageIndex*@pageSize 
end
exec GetStudentInfoPage 2, 2

C# 学习笔记(19)操作SQL Server下_第3张图片

--存储过程 根据省名得到城市表
create proc GetCityInfo 
	@provinceName nvarchar(10)
as
begin
	select cityTable.id, cityName from cityTable
inner join provinceTable on cityTable.provinceID = provinceTable.id
where provinceTable.province = @provinceName
end
exec GetCityInfo '河北'

数据库随便填了一些数据,不完整
C# 学习笔记(19)操作SQL Server下_第4张图片

利用ADO.net操作数据库

  1. 创建链接字符串
//设置数据库连接字符串
//Serever: 表示要连接的SQL Server 服务端所在的机器(可以是ip, 可以是hostname)  . 代表本机
//Database: 数据库名称
//User Id:  用户名
//Password: 密码
//Connection Timeout: 链接超时时间
MySqlHelper.conStr = "Data Source = .;Database = TestDB; User Id = sa; Password= 12345678; Connection Timeout = 5;";

  1. 编写sql语句

例如要查询 studentInfoTable 表数据条数
SQL语句为

select count(*) from studentInfoTable

c#中将其转换成字符串即可

string sql = "select count(*) from studentInfoTable";
  1. 添加sql参数(非必要)

如果SQL语句需要参数,例如查询一页学生数据
SQL语句为

exec GetStudentInfoPage 2, 2

c#中

//sql 语句
string sql = "exec GetStudentInfoPage @page, @size";

//sql 语句参数
SqlParameter page = new SqlParameter("@page", _currentPage);
SqlParameter pageSize = new SqlParameter("@size", PageSize);
  1. 查询并显示数据
//执行不带参 sql语句
int count = (int)MySqlHelper.ExecuteScalar(sql);
//执行带参 sql语句
DataTable dt = MySqlHelper.ExecuteTable(sql, page, pageSize);
  • 图表中显示查询到的表
//为GridView的列绑定数据源  也就是将dataGridViewSQL的列和 sql查出来表的列名绑定起来
dataGridViewSQL.Columns[0].DataPropertyName = "学生编号";
dataGridViewSQL.Columns[1].DataPropertyName = "姓名";
dataGridViewSQL.Columns[2].DataPropertyName = "性别";
dataGridViewSQL.Columns[3].DataPropertyName = "班级";
dataGridViewSQL.Columns[4].DataPropertyName = "家庭地址";

//禁止自动创建列
dataGridViewSQL.AutoGenerateColumns = false;

//绑定数据源
dataGridViewSQL.DataSource = dt;
  • combox中显示查询到的一列数据
//sql 语句
string sql = "select * from provinceTable";

//执行sql语句
DataTable dt = MySqlHelper.ExecuteTable(sql);

//为combox的列绑定数据源  也就是将combox和 sql查出来表的列名绑定起来
cmbProvince.DisplayMember = "province";
//绑定数据源
cmbProvince.DataSource = dt;

C# 学习笔记(19)操作SQL Server下_第5张图片
源码地址 https://download.csdn.net/download/weixin_42378319/20681950

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

namespace CSharp_SQL
{
     
    public partial class Form1 : Form
    {
     
        int PageMax = 1;
        int PageSize = 3;
        int _currentPage = 1;
        int CurrentPage
        {
     
            get {
      return _currentPage; }
            set 
            {
     
                //sql 语句 查询行数
                string sql = "select count(*) from studentInfoTable";

                //执行sql语句
                PageMax = (int)MySqlHelper.ExecuteScalar(sql);
                PageMax = (PageMax + PageSize - 1) / PageSize;
                if (value < 1)
                {
     
                    _currentPage = PageMax;
                }
                else if(value > PageMax)
                {
     
                    _currentPage = 1;
                }
                else
                {
     
                    _currentPage = value;
                }

                txbPage.Text = _currentPage.ToString()+"/"+PageMax.ToString();

                //sql 语句
                sql = "exec GetStudentInfoPage @page, @size";

                //sql 语句参数
                SqlParameter page = new SqlParameter("@page", _currentPage);
                SqlParameter pageSize = new SqlParameter("@size", PageSize);

                //执行sql语句
                DataTable dt = MySqlHelper.ExecuteTable(sql, page, pageSize);

                //为GridView的列绑定数据源  也就是将dataGridViewSQL的列和 sql查出来表的列名绑定起来
                dataGridViewSQL.Columns[0].DataPropertyName = "学生编号";
                dataGridViewSQL.Columns[1].DataPropertyName = "姓名";
                dataGridViewSQL.Columns[2].DataPropertyName = "性别";
                dataGridViewSQL.Columns[3].DataPropertyName = "班级";
                dataGridViewSQL.Columns[4].DataPropertyName = "家庭地址";

                //禁止自动创建列
                dataGridViewSQL.AutoGenerateColumns = false;

                //绑定数据源
                dataGridViewSQL.DataSource = dt;
            }
        }
        
        public Form1()
        {
     
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
     
            //开启表格的双缓冲,避免闪烁
            MyDataGridViewDoubleBuffer.SetDoubleBuffered(dataGridViewSQL, true);

            //设置数据库连接字符串
            //Serever: 表示要连接的SQL Server 服务端所在的机器(可以是ip, 可以是hostname)  . 代表本机
            //Database: 数据库名称
            //User Id:  用户名
            //Password: 密码
            //Connection Timeout: 链接超时时间
            MySqlHelper.conStr = "Data Source = .;Database = TestDB; User Id = sa; Password= 12345678; Connection Timeout = 5;";

            CurrentPage = 1;
        }

        private void labFrontPage_Click(object sender, EventArgs e)
        {
     
            CurrentPage -= 1;
        }

        private void labBackPage_Click(object sender, EventArgs e)
        {
     
            CurrentPage += 1;
        }

        private void txbPage_TextChanged(object sender, EventArgs e)
        {
     
            try
            {
     
                CurrentPage = int.Parse(txbPage.Text);
            }
            catch
            {
     

            }
        }

        private void txbPage_MouseDown(object sender, MouseEventArgs e)
        {
     
            txbPage.SelectAll();
        }

        private voidToolStripMenuItem_Click(object sender, EventArgs e)
        {
     
            FormSQL formSQL = new FormSQL((int)dataGridViewSQL.SelectedRows[0].Cells[0].Value, (string)dataGridViewSQL.SelectedRows[0].Cells[1].Value, (string)dataGridViewSQL.SelectedRows[0].Cells[2].Value, (string)dataGridViewSQL.SelectedRows[0].Cells[3].Value);
            formSQL.Text = "增/改数据";
            formSQL.ShowDialog();

            //刷新
            CurrentPage = CurrentPage;
        }

        private voidToolStripMenuItem_Click(object sender, EventArgs e)
        {
     
            foreach (DataGridViewRow item in dataGridViewSQL.SelectedRows)
            {
     
                //sql 语句
                string sql = "delete from studentTable where studentTable.id = @id";

                //sql 语句参数
                SqlParameter id = new SqlParameter("@id", item.Cells[0].Value);

                //执行sql语句
                DataTable dt = MySqlHelper.ExecuteTable(sql, id);

                //刷新
                CurrentPage = CurrentPage;
            }
        }
    }
}

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

namespace CSharp_SQL
{
     
    public partial class FormSQL : Form
    {
     
        int StudentID = 0;
        DataTable gradeDT, cityDT;

        public FormSQL(int studentID, string name, string gender, string grade)
        {
     
            InitializeComponent();

            #region 查询数据库 获取省份和班级信息
            //sql 语句
            string sql = "select * from provinceTable";

            //执行sql语句
            DataTable dt = MySqlHelper.ExecuteTable(sql);

            //为combox的列绑定数据源  也就是将combox和 sql查出来表的列名绑定起来
            cmbProvince.DisplayMember = "province";
            //绑定数据源
            cmbProvince.DataSource = dt;

            sql = "select * from gradeTable";

            //执行sql语句
            gradeDT = MySqlHelper.ExecuteTable(sql);

            //为combox的列绑定数据源  也就是将combox和 sql查出来表的列名绑定起来
            cmbStudentGrade.DisplayMember = "name";
            //绑定数据源
            cmbStudentGrade.DataSource = gradeDT;
            #endregion

            txbStudentName.Text = name;
            if(gender == "男")
            {
     
                radMan.Checked = true;
            }
            else
            {
     
                radWoman.Checked = true;
            }
            cmbStudentGrade.Text = grade;

            //获取学生地址信息
            sql = "select * from studentMinuteInfoTable where 学生编号 = @id";

            //sql 语句参数
            SqlParameter id = new SqlParameter("@id", studentID);

            //执行sql语句
            dt = MySqlHelper.ExecuteTable(sql, id);

            cmbProvince.Text = (string)dt.Rows[0].ItemArray[4];
            cmbCity.Text = (string)dt.Rows[0].ItemArray[5];

            if(dt.Rows[0].ItemArray[6] != System.DBNull.Value)
                txbStudentAddr.Text = (string)dt.Rows[0].ItemArray[6];

            StudentID = studentID;
        }

        /// 
        /// 省变化时,市信息跟着变化
        /// 
        /// 
        /// 
        private void cmbProvince_SelectedIndexChanged(object sender, EventArgs e)
        {
     
            //sql 语句
            string sql = "exec GetCityInfo @provinceName";

            //sql 语句参数
            SqlParameter provinceName = new SqlParameter("@provinceName", cmbProvince.Text);

            //执行sql语句
            cityDT = MySqlHelper.ExecuteTable(sql, provinceName);

            //为combox的列绑定数据源  也就是将combox和 sql查出来表的列名绑定起来
            cmbCity.DisplayMember = "cityName";
            //绑定数据源
            cmbCity.DataSource = cityDT;
        }

        private void btnAdd_Click(object sender, EventArgs e)
        {
     
            //sql 语句
            string sql = "insert into studentTable(gradeID, name, gender, cityID, address) Values(@gradeID, @name, @gender, @cityID, @address)";
            //sql 语句参数
            SqlParameter gradeID = new SqlParameter("@gradeID", gradeDT.Rows[cmbStudentGrade.SelectedIndex].ItemArray[0]);
            SqlParameter name = new SqlParameter("@name", txbStudentName.Text);
            SqlParameter gender;
            if(radMan.Checked)
            {
     
                gender = new SqlParameter("@gender", true);
            }
            else
            {
     
                gender = new SqlParameter("@gender", false);
            }

            SqlParameter cityID = new SqlParameter("@cityID", cityDT.Rows[cmbCity.SelectedIndex].ItemArray[0]);
            SqlParameter address = new SqlParameter("@address", txbStudentAddr.Text);

            MySqlHelper.ExecuteNonQuery(sql, gradeID, name, gender, cityID, address);

            this.Close();
        }

        private void btnUpdate_Click(object sender, EventArgs e)
        {
     
            //sql 语句
            string sql = "update studentTable set gradeID = @gradeID, name = @name, gender = @gender, cityID = @cityID, address = @address where id = @id";
            //sql 语句参数
            SqlParameter id = new SqlParameter("@id", StudentID);
            SqlParameter gradeID = new SqlParameter("@gradeID", gradeDT.Rows[cmbStudentGrade.SelectedIndex].ItemArray[0]);
            SqlParameter name = new SqlParameter("@name", txbStudentName.Text);
            SqlParameter gender;
            if (radMan.Checked)
            {
     
                gender = new SqlParameter("@gender", true);
            }
            else
            {
     
                gender = new SqlParameter("@gender", false);
            }

            SqlParameter cityID = new SqlParameter("@cityID", cityDT.Rows[cmbCity.SelectedIndex].ItemArray[0]);
            SqlParameter address = new SqlParameter("@address", txbStudentAddr.Text);

            MySqlHelper.ExecuteNonQuery(sql, gradeID, name, gender, cityID, address, id);

            this.Close();
        }
    }
}

你可能感兴趣的:(c#学习笔记,c#,sql,嵌入式,物联网)