C# 学习笔记(19)操作SQL Server下
Posted 不咸不要钱
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了C# 学习笔记(19)操作SQL Server下相关的知识,希望对你有一定的参考价值。
C# 学习笔记(19)操作SQL Server下
ADO.net操作数据库
这应该是比较老的技术了,以后有空的话学学 Linq
/// <summary>
/// 数据库使用类
/// </summary>
public static class mysqlHelper
{
/// <summary>
/// 1.数据库连接字符串
/// </summary>
public static string conStr;
/// <summary>
/// SQL 增 删 改
/// </summary>
/// <param name="sql">sql命令</param>
/// <param name="ps">sql参数</param>
/// <returns></returns>
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;
}
}
/// <summary>
/// SQL 查询一行数据
/// </summary>
/// <param name="sql"></param>
/// <param name="ps"></param>
/// <returns></returns>
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;
}
}
/// <summary>
/// SQL 查询一块数据,并把数据存放在一个表中
/// </summary>
/// <param name="sql">命令</param>
/// <param name="ps">参数</param>
/// <returns>内存中的表</returns>
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;
}
}
/// <summary>
/// SQL 查询一块数据
/// </summary>
/// <param name="sql"></param>
/// <param name="ps"></param>
/// <returns></returns>
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
--创建视图 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
--获取一页学生信息
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
--存储过程 根据省名得到城市表
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 '河北'
数据库随便填了一些数据,不完整
利用ADO.net操作数据库
- 创建链接字符串
//设置数据库连接字符串
//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;";
- 编写sql语句
例如要查询 studentInfoTable 表数据条数
SQL语句为
select count(*) from studentInfoTable
c#中将其转换成字符串即可
string sql = "select count(*) from studentInfoTable";
- 添加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);
- 查询并显示数据
//执行不带参 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;
源码地址 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 void 增ToolStripMenuItem_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 void 删ToolStripMenuItem_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 =<以上是关于C# 学习笔记(19)操作SQL Server下的主要内容,如果未能解决你的问题,请参考以下文章
SQL Server 2012 案例教程(贾祥素)——学习笔记