-
Notifications
You must be signed in to change notification settings - Fork 18
02数据库连接
Windr07 edited this page Sep 23, 2020
·
1 revision
-
WLib提供了
DbHelper
类封装简化ADO.NET的操作; -
支持包括Oracle、SQLServer、MySQL、Sqlite和通过ODBC、OLEDB连接的数据源(例如Access、Excel、dbf等),可扩展支持其他类型数据源。
- 特定数据库的查询
//需添加引用: using WLib.Database;
DbHelper dbHelper = DbHelper.SqlServerHelper("127.0.0.1", "databaseName", "username", "password");
DataTable table = dbHelper.GetDataTable("select * from table1");
-
通用数据库的查询
通过枚举
EDbProviderType
指定数据源、使用连接字符串构建查询:
DbHelper dbHelper = DbHelper.GetDbHelper("Data Source=127.0.01;Initial Catalog=myDataBase;User Id=username;Password=password;", EDbProviderType.SqlServer, 30);
DataTable table = dbHelper.GetDataTable("select * from table1");
-
支持的数据源类型
通过
EDbProviderType
枚举说明支持的数据源类型包括:-
Oracle、SQLServer、MySQL、Sqlite等数据库;
-
各类通过ODBC、OLEDB连接的数据源(包括Access、Excel、dbf等);
-
通过修改
EDbProviderType
枚举及枚举值的Description特性来扩展支持其他数据源。
-
-
查询ArcGIS数据
ArcGIS提供的数据(shp\gdb\mdb\dbf),在安装了ESRI OLE DB提供程序后同样可以通过DbHelper进行简单查询,示例如下:
DbHelper dbHelper = DbHelper.GetShpMdbGdbHelper(@"c:\River.dbf");
DataTable dataTable = dbHelper.GetDataTable(@"select * from River where RiverName = 'Pearl River'");
-
连接超时和命令执行超时设置
dbHelper.ConnectionTimeOut = 10;//设置连接超时时间(秒) dbHelper.CommandTimeOut = 60;//设置命令执行超时时间(秒)
-
监控执行的SQL语句
通过
DbHelper.PreExcute
事件监控执行的SQL语句,方便日志记录或调试:
dbHelper1.PreExcute += (sender, e) => Console.WriteLine(e.Sql);
-
由于不同连接方式下、不同数据库的连接字符串不同,在设置连接字符串时通常容易出错,
解决此问题推荐参考网站:https://www.connectionstrings.com/
-
在
DbHelper
类中,也提供了一些辅助方法构建部分常用数据库的连接字符串,例如:
var connectionString1 = DbHelper.Access_OleDb4("c:\data\mydb.mdb", "testUser", "123456");
var connectionString2 = DbHelper.Excel_OleDb("c:\data\data.xlsx", "YES", 1);
var connectionString3 = DbHelper.MySql("127.0.0.1","testDb", "aa","123456");
var connectionString4 = DbHelper.Sqlite("c:\Data\mydb.db");
aaa