GZDBHelperDemo 一

1.新建Window窗体项目GZDBHelperDemo

2.从Nuget添加GZDBHelper引用

image

添加完成后会出现GZDBHelper的引用

image

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数据库种新建两张测试表,表结构如下

image

预览:

image

创建语句:

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

界面:

image

功能代码:

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);
            }
        }
    }

添加控件到主界面:

image

启动运行程序,测试!!

测试步骤!

1.点击刷新,初始化数据源,第一次没有数据源的

2.添加3条数据 编号是自增字段,所以只读,不可更改

     image

3.删除第二条数据,先选中第二条,再点击删除选中行按钮

      image

4.删除第二行后,点提交更改

     image

       提示保存成功,后台看数据库表里面已经新增了两条数据

       image

        就是这么简单

5.删除user3,同时再新增user4

        image

        提交更改后,再看下后台数据

          image

         已经成功删除了user3并同时新增了user4

6.演示对象提交(增删改)一次智能提交一种类型的更改

新增一个用户控件UpdateModel

界面同

image

功能代码:

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; }
    }

添加控件到主界面:

image

启动运行程序,测试!!

测试步骤!

1.点击刷新,初始化数据源,第一次没有数据源的

2.点击新增按钮新增一条数据,然后提交,查看后台数据

image

image

3.在连续新增两条数据

image

4.选中第二条数据,修改然后提交

image

image

      

         完成!

注意:模型对象方式提交不能批量提交不通类型的,比如不能像DataTable提交那样一个集合里既有删除也又修改同时还有增加,一次性提交,模型只能一次提交一个类型的集合,比如我可以一次提交两个对象,单这两个对象要么都是新增要么都是修改要么都是删除,不能混合

对象提交参数用params关键字注释,标识一次可以提交多个,比如:

DB.Update<Table1Model>(model1,model2);

此时model1和model2都必须是Table1Model类型,这行代码表示添加两条数据

模型修改不能修改主键,如果修改主键值的话会无法正确修改!如果要修改主键值,请尝试其他方式

接下来会后续补充:

执行存储过程和SQL语句(带参数查询)

多数据库配置

Access,Sqlite,Oracle数据库配置

事务方式提交

在一个链接中分批提交

带返回值的参数处理

敬请期待

详细文档参考:http://www.yesdotnet.com/archive/gzhelper/1614552868.html

慎于行,敏于思!GGGGGG
原文地址:https://www.cnblogs.com/GarsonZhang/p/5997596.html