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. js实现下滑加载更多的效果

    var stop=true;$(window).scroll(function(){ totalheight = parseFloat($(window).height()) + parseFloat ...

  2. 委托学习笔记后续:泛型委托及委托中所涉及到匿名方法、Lambda表达式

    引言: 最初学习c#时,感觉委托.事件这块很难,其中在学习的过程中还写了一篇学习笔记:委托.事件学习笔记.今天重新温故委托.事件,并且把最近学习到和委托相关的匿名方法.Lambda表达式及泛型委托记录 ...

  3. varsh4.1 安装清除cache

    yum install automake autoconf ncurses-devel libxslt groff pkgconfig python-docutils readline-devel - ...

  4. 手机端页面自适应解决方案—rem布局

    只需在页面引入这段原生js代码就可以了 (function (doc, win) { var docEl = doc.documentElement, resizeEvt = 'orientation ...

  5. css常用鼠标指针形状代码

    默认 default 文字/编辑 text 自动 auto 手形 pointer, hand(hand是IE专有) 可移动对象 move 不允许 not-allowed 无法释放 no-drop 等待 ...

  6. WebForm 内置对象2

    Session: 与Cookies相比 相同点:每一台电脑访问服务器,都会是独立的一套session,key值都一样,但是内容都是不一样的 以上所有内容,都跟cookies一样 不同点: 1.Sess ...

  7. 详解clientHeight、offsetHeight、scrollHeight

    关于clientHeight.offsetHeight.scrollHeight   window.screen.availWidth 返回当前屏幕宽度(空白空间)  window.screen.av ...

  8. Android--我的Butterknife黄油刀怎么找不到控件了!!!

    1,首先说一下Butterknife这个插件真的挺好用的,不过最近几天在写demo的时候发现总是出现绑定的view是空的,当时着急写代码,也没有深究一下,直接手工findViewbyid了,今天下午写 ...

  9. Java中关于先有鸡还是先有蛋的问题----Class&Object

    在Java中,我们常常会看到一个类型:Class.并且在类似Person.class,cache.getClass()等代码中见到它的身影. 众所周知,Class是用来描述一个类的类型,而Object ...

  10. nodejs cookie管理

    Cookie 管理 我们可以使用中间件向 Node.js 服务器发送 cookie 信息,以下代码输出了客户端发送的 cookie 信息: // express_cookie.js 文件 var ex ...