GZDBHelperDemo 一
1.新建Window窗体项目GZDBHelperDemo
2.从Nuget添加GZDBHelper引用
添加完成后会出现GZDBHelper的引用
3.添加数据库链接管理类
添加类库文件:DatabaseFactoryEx.cs
public class DatabaseFactoryEx
{
private static GZDBHelper.IDatabase db; public static GZDBHelper.IDatabase CreateDatabase()
{
if (db == null)
{
/*
* 添加System.Configuration引用
* 配置文件种新增节点
* <connectionStrings>
* <add name="dbconnectionstr" providerName="System.Data.SqlClient" connectionString="Server = *;Database = *;User ID = *;Password = *;Trusted_Connection = False" />
* </connectionStrings>
* string ProviderName = System.Configuration.ConfigurationManager.ConnectionStrings["dbconnectionstr"].ProviderName;
* string connectionstr = System.Configuration.ConfigurationManager.ConnectionStrings["dbconnectionstr"].ConnectionString;
*/ const string server = "(local)";
const string dbName = "Test";
const string userID = "sa";
const string Pwd = "test"; string connectionstr = GZDBHelper.ConnectionStrings.BuildMSSQLConnectionString(server, dbName, userID, Pwd);
string ProviderName = GZDBHelper.ConnectionStrings.ProviderNames.ProviderNameForMSSql;
bool b = GZDBHelper.DatabaseFactory.Validate(connectionstr, ProviderName);
db = GZDBHelper.DatabaseFactory.CreateDatabase(connectionstr, ProviderName);
}
return db;
}
}
4.在MSSQL数据库种新建两张测试表,表结构如下

预览:
创建语句:
if exists (select 1
from sysobjects
where id = object_id('dbo.tb_table1')
and type = 'U')
drop table dbo.tb_table1
go if exists (select 1
from sysobjects
where id = object_id('dbo.tb_table2')
and type = 'U')
drop table dbo.tb_table2
go drop schema dbo
go /*==============================================================*/
/* User: dbo */
/*==============================================================*/
create schema dbo
go /*==============================================================*/
/* Table: tb_table1 */
/*==============================================================*/
create table dbo.tb_table1 (
isid int identity(1, 1),
UserID varchar(20) collate Chinese_PRC_CI_AS null,
Password varchar(50) collate Chinese_PRC_CI_AS null,
Email varchar(50) collate Chinese_PRC_CI_AS null,
constraint PK_tb_table1 primary key (isid)
on "PRIMARY"
)
on "PRIMARY"
go /*==============================================================*/
/* Table: tb_table2 */
/*==============================================================*/
create table dbo.tb_table2 (
isid int identity(1, 1),
DocNo varchar(20) collate Chinese_PRC_CI_AS not null,
UserName varchar(50) collate Chinese_PRC_CI_AS null,
ProductName varchar(50) collate Chinese_PRC_CI_AS null,
CreateBy varchar(20) collate Chinese_PRC_CI_AS null,
constraint PK_tb_table2 primary key (DocNo)
on "PRIMARY"
)
on "PRIMARY"
go
5.演示DataTable方式提交(增删改)可同时提交类型的更改
新增一个用户控件UpdateDataTable
界面:
功能代码:
public partial class DataTableUpdate : UserControl
{
/// <summary>
/// 数据库操作对象
/// </summary>
GZDBHelper.IDatabase DB; /// <summary>
/// 数据源
/// </summary>
DataTable DataSource; // 构造器
public DataTableUpdate()
{
InitializeComponent();
if (CheckDesingModel.IsDesingMode) return;// 创建数据库链接对象
DB = DatabaseFactoryEx.CreateDatabase();
dataGridView1.AutoGenerateColumns = false;
} //加载数据
private void btn_LoadData_Click(object sender, EventArgs e)
{
if (DataSource != null
&& DataSource.GetChanges() != null
&& DataSource.GetChanges().Rows.Count > 0)
{
if (Msg.AskQuestion("当前对数据的更改没有提交到数据库,确定放弃更改吗?") == false)
return;
}
string sql = "SELECT * FROM tb_table1";
DataSource = DB.GetTable(sql, "table1", null);
dataGridView1.DataSource = DataSource;
}
//删除
private void btn_Delete_Click(object sender, EventArgs e)
{
DataSource.Rows[dataGridView1.CurrentRow.Index].Delete();
}
//保存 提交到数据库
private void btn_Save_Click(object sender, EventArgs e)
{
string sql = "SELECT * FROM tb_table1";
bool success = DB.Update(DataSource, sql);
if (success == true)
{
Msg.ShowInformation("保存成功!");
DataSource.AcceptChanges();
btn_LoadData_Click(null, null);
}
}
}添加控件到主界面:
启动运行程序,测试!!
测试步骤!
1.点击刷新,初始化数据源,第一次没有数据源的
2.添加3条数据 编号是自增字段,所以只读,不可更改
3.删除第二条数据,先选中第二条,再点击删除选中行按钮
4.删除第二行后,点提交更改
提示保存成功,后台看数据库表里面已经新增了两条数据
就是这么简单
5.删除user3,同时再新增user4
提交更改后,再看下后台数据
已经成功删除了user3并同时新增了user4
6.演示对象提交(增删改)一次智能提交一种类型的更改
新增一个用户控件UpdateModel
界面同
功能代码:
public partial class UpdateModel : UserControl
{
/// <summary>
/// 数据库操作对象
/// </summary>
GZDBHelper.IDatabase DB; /// <summary>
/// 数据源
/// </summary>
DataTable DataSource; public UpdateModel()
{
InitializeComponent();
if (CheckDesingModel.IsDesingMode) return;
dataGridView1.AutoGenerateColumns = false;
//创建数据库操作对象
DB = DatabaseFactoryEx.CreateDatabase();
}
//刷新
private void btn_LoadData_Click(object sender, EventArgs e)
{
if (DataSource != null
&& DataSource.GetChanges() != null
&& DataSource.GetChanges().Rows.Count > 0)
{
if (Msg.AskQuestion("当前对数据的更改没有提交到数据库,确定放弃更改吗?") == false)
return;
}
string sql = "SELECT * FROM tb_table1";
DataSource = DB.GetTable(sql, "table1", null);
dataGridView1.DataSource = DataSource;
}
//删除
private void btn_Delete_Click(object sender, EventArgs e)
{
bool success = DB.Delete<Table1Model>(CurrentModel);
if (success == true)
{
Msg.ShowInformation("保存成功!");
btn_LoadData_Click(null, null);
}
}
//新增
private void btn_Add_Click(object sender, EventArgs e)
{
CurrentModel = new Table1Model(); BindData();
} //绑定数据
private void BindData()
{
txtisid.DataBindings.Clear();
txtUserID.DataBindings.Clear();
txtPassword.DataBindings.Clear();
txtEmail.DataBindings.Clear(); txtisid.DataBindings.Add("Text", CurrentModel, "isid");
txtUserID.DataBindings.Add("Text", CurrentModel, "ID");
txtPassword.DataBindings.Add("Text", CurrentModel, "Password");
txtEmail.DataBindings.Add("Text", CurrentModel, "Email");
} //保存
private void btn_Save_Click(object sender, EventArgs e)
{
bool success = false;
if (CurrentModel.isid > 0)
success = DB.Update<Table1Model>(CurrentModel);
else
success = DB.Insert<Table1Model>(CurrentModel);
if (success == true)
{
Msg.ShowInformation("保存成功!");
btn_LoadData_Click(null, null);
}
} Table1Model CurrentModel; private void dataGridView1_SelectionChanged(object sender, EventArgs e)
{
CurrentModel = new Table1Model();
if (dataGridView1.CurrentRow.Index < 0)
return;
if (dataGridView1.CurrentRow.Index >= DataSource.Rows.Count)
return;
DataRow dr = DataSource.Rows[dataGridView1.CurrentRow.Index];
CurrentModel.isid = Convert.ToInt32(dr["isid"]);
CurrentModel.ID = dr["UserID"].ToString();
CurrentModel.Password = dr["Password"].ToString();
CurrentModel.Email = dr["Email"].ToString(); BindData(); } }
//定义数据库对应的表名
[GZDBHelper.Attributes.SourceTableName("tb_table1")]
public class Table1Model
{
public int isid { get; set; }
//设置对应数据库的列名,如果不设置默认同名
[GZDBHelper.Attributes.SourceColumnName("UserID")]
public string ID { get; set; }
public string Password { get; set; }
public string Email { get; set; }
}添加控件到主界面:
启动运行程序,测试!!
测试步骤!
1.点击刷新,初始化数据源,第一次没有数据源的
2.点击新增按钮新增一条数据,然后提交,查看后台数据
3.在连续新增两条数据
4.选中第二条数据,修改然后提交
完成!
注意:模型对象方式提交不能批量提交不通类型的,比如不能像DataTable提交那样一个集合里既有删除也又修改同时还有增加,一次性提交,模型只能一次提交一个类型的集合,比如我可以一次提交两个对象,单这两个对象要么都是新增要么都是修改要么都是删除,不能混合
对象提交参数用params关键字注释,标识一次可以提交多个,比如:
DB.Update<Table1Model>(model1,model2);
此时model1和model2都必须是Table1Model类型,这行代码表示添加两条数据
模型修改不能修改主键,如果修改主键值的话会无法正确修改!如果要修改主键值,请尝试其他方式
接下来会后续补充:
执行存储过程和SQL语句(带参数查询)
多数据库配置
Access,Sqlite,Oracle数据库配置
事务方式提交
在一个链接中分批提交
带返回值的参数处理
敬请期待
GZDBHelperDemo 一的更多相关文章
随机推荐
- linux io stack
- IE or Chrome can not use localhost, firefox can works.
因为服务器开启'localhost:9999",使用IE无法登陆,firefox下正常. 遂查看cookie,果然没有写入. stackoverflow.com: "ie enab ...
- 教你分分钟学会用python爬虫框架Scrapy爬取心目中的女神
本博文将带领你从入门到精通爬虫框架Scrapy,最终具备爬取任何网页的数据的能力.本文以校花网为例进行爬取,校花网:http://www.xiaohuar.com/,让你体验爬取校花的成就感. Scr ...
- smarty 模板几个例子
一.assign和display方法的使用以及几个变量调节器 header("content-type:text/html;charset=utf-8");//加载Smarty引擎 ...
- 数据结构看书笔记(二)--算法(Algorithm)简介
算法:是解决问题求解步骤的描述,在计算机中表现为指令的有限序列,并且每条指令表示一个或多个操作. 算法的特性:算法具有五个特性:输入.输出.有穷性.确定性.可行性 输入输出:算法具有零个或多个输入:至 ...
- poj 1835 宇航员
http://poj.org/problem?id=1835 宇航员 Time Limit: 2000MS Memory Limit: 30000K Total Submissions: 4802 ...
- [原创]java WEB学习笔记107:Spring学习---AOP切面的优先级,重用切点表达式
本博客的目的:①总结自己的学习过程,相当于学习笔记 ②将自己的经验分享给大家,相互学习,互相交流,不可商用 内容难免出现问题,欢迎指正,交流,探讨,可以留言,也可以通过以下方式联系. 本人互联网技术爱 ...
- ubuntu配置tftp服务
ubuntu配置TFTP服务: TFTP是用来下载远程文件的最简单的网络协议,基于UDP协议.xinetd是新一代的网络守护进程服务程序,经常用于管理多种轻量型internet服务. sudo apt ...
- centos安装mono
1.查看mono最新版本 http://download.mono-project.com/sources/mono 2.安装依赖环境 sudo yum install cmake automake ...
- PB函数大全
PB函数大全 Abs()功能计算绝对值.语法Abs ( n )参数n:要得到绝对值的数值型变量或表达式返回值返回值的数据类型与n的数据类型相同,函数执行成功时返回n的绝对值.如果参数n的值为NULL, ...

















