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 一的更多相关文章

随机推荐

  1. C++学习笔记 指针与引用

    指针与引用  1. 指针 (1) 指针是一个变量(实体),存储的是一个地址,指向内存的一个存储单元,指针可以为空 (2) 指针可以为空,在声明定义时可以不初始化 (3) 指针在初始化之后可以重新指向其 ...

  2. 后移动互联网时代:到底还要不要开发一个App?

    后移动互联网时代,到底是什么样的一个时代? 首先,后移动互联网时代中,产生头部应用的几率变小了,像微信这样巨头式的App很难在产生第二个.其次,后移动互联网时代,物联网发展迅速,所有的智能硬件都需要一 ...

  3. kdiff3的主窗口说明 Base Local Remote 分别代表什么分支

  4. AngularJS 2.0

    https://angular.io/docs/ts/latest/guide/learning-angular.html QuickStart: git clone https://github.c ...

  5. HDU 5053 the Sum of Cube(简单数论)

    http://acm.hdu.edu.cn/showproblem.php?pid=5053 题目大意: 求出A^3+(A+1)^3+(A+2)^3+...+B^3和是多少 解题思路: 设f(n)=1 ...

  6. Linux 发行版本及其基于

    Independent ---> Debian Debian/Ubuntu(LTS) ---> Linux Mint ---> Linux Lite Debian/Ubuntu -- ...

  7. AIX UNIX 系统管理、维护与高可用集群建设——数据库结构设计

    在对数据库类应用进行优化的过程中我们了解到一个原则,即思想上要从结构设计抓起,按照下面的顺序: 1.数据库逻辑结构设计和物理设计. 2.数据库对象部署和SQL代码编写. 3.数据库实例性能调整和优化. ...

  8. CentOS 6.5下Zabbix的安装配置

    1.确保开发环境lamp已经安装 2.下载zabbix 官方下载地址:http://www.zabbix.com/download.php 选择和自己系统对应的版本,这里选择安装与Linux内核为2. ...

  9. mysql5.6.23免安装配置

    1.官网下载,并解压 2.环境变量,path下,追加mysql的bin路径D:\Program Files\mysql\bin; 3.mysql目录下的my-default.ini重命名为my.ini ...

  10. EditPlus 3.6 中文版已经发布(2013年12月17日)

    新版的EditPlus 3.6修复了多项问题,并新增了函数列表面板.按F2.Ctrl+F2等快捷键可弹出输入提示窗格. 我已同步汉化最新版,请点击右上角的连接下载.