[C#]ADO访问多数据库的C#库

本文介绍了一个使用C#编写的库,支持通过ADO方式访问多种数据库,包括OLE DB、MySQL、SQL Server和Oracle,并提供了示例代码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

[+]
  1. 一C Database 库
  2. 二使用示例
  3. 三注意事项

[C#]ADO访问多数据库的C#库

罗朝辉 (http://blog.youkuaiyun.com/kesalin/)

本文遵循“署名-非商业用途-保持一致”创作公用协议

一,C# Database 库

整了一个支持通过ADO方式访问多种数据库(OLE,MySQL,SQL Server,Oracle)的 C# 库 Database。实现相当简单,用工厂方法创建各种数据库访问的 wrapper 类即可。

源码下载:点此下载
或访问 Github:https://github.com/kesalin/CSharpSnippet/tree/master/Database

类图如下:


IDatabase 是对外公开的接口类,其中定义了一堆操作数据库的接口方法;
DatabaseFactory 是窗口数据库的工厂类;
DatabaseType 是一个数据库类型的枚举;
DatabaseHelper 封装一些和数据库相关的常用的小工具方法,如便捷地创建 connection string,从 dataset 中读取值等。

二,使用示例

示例代码如下:

  1. internal class Program  
  2. {  
  3.     private IDatabase _db;  
  4.     private const DatabaseType _dbType = DatabaseType.MySQL; 
  5.  
  6.     #region Database related   
  7.   
  8.     // You need to create a MySQL database named "sample" with columns   
  9.     // id(int), Name(varchar(45)), Address(varchar(45)), Age(int) for this test.  
  10.     //    
  11.     private void CreateDatabase()  
  12.     {  
  13.         if (_db == null)  
  14.         {  
  15.             // Setup you database information here.  
  16.             //   
  17.             var connStr = DatabaseHelper.CreateConnectionString(_dbType, "localhost""sample""root""123456");  
  18.             _db = DatabaseFactory.CreateDatabase(_dbType, connStr);  
  19.   
  20.             if (_db == null)  
  21.                 Console.WriteLine(" >> Failed to create database with connection string {0}.", connStr);  
  22.             else  
  23.                 Console.WriteLine(" >> Created database.");  
  24.         }  
  25.     }  
  26.   
  27.     private void CloseDatabase()  
  28.     {  
  29.         if (_db != null)  
  30.         {  
  31.             _db.Dispose();  
  32.             _db = null;  
  33.         }      
  34.     }  
  35.   
  36.     public void TestInsert()  
  37.     {  
  38.         if (_db == null)  
  39.             return;  
  40.   
  41.         const string sqlCmd = "insert into customer (id, Name,Address,Age) values (0,'飘飘白云','上海张江高科',28)";  
  42.   
  43.         try  
  44.         {  
  45.             _db.Open();  
  46.             _db.ExcuteSql(sqlCmd);  
  47.   
  48.             Console.WriteLine(" >> Succeed. {0}", sqlCmd);  
  49.         }  
  50.         catch (Exception ex)  
  51.         {  
  52.             Console.WriteLine(" >> Failed to {0}. {1}", sqlCmd, ex.Message);  
  53.         }  
  54.         finally  
  55.         {  
  56.             _db.Close();  
  57.         }  
  58.     }  
  59.   
  60.     public void TestFind()  
  61.     {  
  62.         if (_db == null)  
  63.             return;  
  64.   
  65.         const string sqlCmd = "select Name,Address,Age from customer where Name='飘飘白云'";  
  66.   
  67.         try  
  68.         {  
  69.             _db.Open();  
  70.             var dataSet = _db.ExcuteSqlForDataSet(sqlCmd);  
  71.             var recordCount = DatabaseHelper.GetRowCount(dataSet);  
  72.   
  73.             Console.WriteLine(" >> Excuted {0}", sqlCmd);  
  74.             Console.WriteLine(" >> Found {0} record.", recordCount);  
  75.   
  76.             for (int i = 0; i < recordCount; i++)  
  77.             {  
  78.                 var name = DatabaseHelper.GetValue(dataSet, i, 0) as string;  
  79.                 var address = DatabaseHelper.GetValue(dataSet, i, 1) as string;  
  80.                 var age = DatabaseHelper.GetIntValue(dataSet, i, 2);  
  81.   
  82.                 Console.WriteLine("    >> Record {0}, Name:{1}, Address:{2}, Age:{3}", i + 1, name, address, age);  
  83.             }  
  84.         }  
  85.         catch (Exception ex)  
  86.         {  
  87.             Console.WriteLine(" >> Failed to {0}. {1}", sqlCmd, ex.Message);  
  88.         }  
  89.         finally  
  90.         {  
  91.             _db.Close();  
  92.         }  
  93.     }  
  94.   
  95.     public void TestUpdate()  
  96.     {  
  97.         if (_db == null)  
  98.             return;  
  99.   
  100.         const string sqlCmd = "update customer set Address='张江高科' where Name='飘飘白云'";  
  101.   
  102.         try  
  103.         {  
  104.             _db.Open();  
  105.             _db.ExcuteSql(sqlCmd);  
  106.   
  107.             Console.WriteLine(" >> Succeed. {0}", sqlCmd);  
  108.         }  
  109.         catch (Exception ex)  
  110.         {  
  111.             Console.WriteLine(" >> Failed to {0}. {1}", sqlCmd, ex.Message);  
  112.         }  
  113.         finally  
  114.         {  
  115.             _db.Close();  
  116.         }  
  117.     }  
  118.   
  119.     public void TestDelete()  
  120.     {  
  121.         if (_db == null)  
  122.             return;  
  123.   
  124.         const string sqlCmd = "delete from customer where Name='飘飘白云'";  
  125.   
  126.         try  
  127.         {  
  128.             _db.Open();  
  129.             _db.ExcuteSql(sqlCmd);  
  130.   
  131.             Console.WriteLine(" >> Succeed. {0}", sqlCmd);  
  132.         }  
  133.         catch (Exception ex)  
  134.         {  
  135.             Console.WriteLine(" >> Failed to {0}. {1}", sqlCmd, ex.Message);  
  136.         }  
  137.         finally  
  138.         {  
  139.             _db.Close();  
  140.         }  
  141.     }  
  142.  
  143.     #endregion   
  144.   
  145.     static void Main(string[] args)  
  146.     {  
  147.         var runner = new Program();  
  148.   
  149.         runner.CreateDatabase();  
  150.   
  151.         runner.TestInsert();  
  152.         runner.TestFind();  
  153.   
  154.         runner.TestUpdate();  
  155.         runner.TestFind();  
  156.   
  157.         runner.TestDelete();  
  158.         runner.TestFind();  
  159.   
  160.         runner.CloseDatabase();  
  161.   
  162.         Console.ReadLine();  
  163.     }  
  164. }  
    internal class Program
    {
        private IDatabase _db;
        private const DatabaseType _dbType = DatabaseType.MySQL;

        #region Database related

        // You need to create a MySQL database named "sample" with columns 
        // id(int), Name(varchar(45)), Address(varchar(45)), Age(int) for this test.
        // 
        private void CreateDatabase()
        {
            if (_db == null)
            {
                // Setup you database information here.
                //
                var connStr = DatabaseHelper.CreateConnectionString(_dbType, "localhost", "sample", "root", "123456");
                _db = DatabaseFactory.CreateDatabase(_dbType, connStr);

                if (_db == null)
                    Console.WriteLine(" >> Failed to create database with connection string {0}.", connStr);
                else
                    Console.WriteLine(" >> Created database.");
            }
        }

        private void CloseDatabase()
        {
            if (_db != null)
            {
                _db.Dispose();
                _db = null;
            }    
        }

        public void TestInsert()
        {
            if (_db == null)
                return;

            const string sqlCmd = "insert into customer (id, Name,Address,Age) values (0,'飘飘白云','上海张江高科',28)";

            try
            {
                _db.Open();
                _db.ExcuteSql(sqlCmd);

                Console.WriteLine(" >> Succeed. {0}", sqlCmd);
            }
            catch (Exception ex)
            {
                Console.WriteLine(" >> Failed to {0}. {1}", sqlCmd, ex.Message);
            }
            finally
            {
                _db.Close();
            }
        }

        public void TestFind()
        {
            if (_db == null)
                return;

            const string sqlCmd = "select Name,Address,Age from customer where Name='飘飘白云'";

            try
            {
                _db.Open();
                var dataSet = _db.ExcuteSqlForDataSet(sqlCmd);
                var recordCount = DatabaseHelper.GetRowCount(dataSet);

                Console.WriteLine(" >> Excuted {0}", sqlCmd);
                Console.WriteLine(" >> Found {0} record.", recordCount);

                for (int i = 0; i < recordCount; i++)
                {
                    var name = DatabaseHelper.GetValue(dataSet, i, 0) as string;
                    var address = DatabaseHelper.GetValue(dataSet, i, 1) as string;
                    var age = DatabaseHelper.GetIntValue(dataSet, i, 2);

                    Console.WriteLine("    >> Record {0}, Name:{1}, Address:{2}, Age:{3}", i + 1, name, address, age);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(" >> Failed to {0}. {1}", sqlCmd, ex.Message);
            }
            finally
            {
                _db.Close();
            }
        }

        public void TestUpdate()
        {
            if (_db == null)
                return;

            const string sqlCmd = "update customer set Address='张江高科' where Name='飘飘白云'";

            try
            {
                _db.Open();
                _db.ExcuteSql(sqlCmd);

                Console.WriteLine(" >> Succeed. {0}", sqlCmd);
            }
            catch (Exception ex)
            {
                Console.WriteLine(" >> Failed to {0}. {1}", sqlCmd, ex.Message);
            }
            finally
            {
                _db.Close();
            }
        }

        public void TestDelete()
        {
            if (_db == null)
                return;

            const string sqlCmd = "delete from customer where Name='飘飘白云'";

            try
            {
                _db.Open();
                _db.ExcuteSql(sqlCmd);

                Console.WriteLine(" >> Succeed. {0}", sqlCmd);
            }
            catch (Exception ex)
            {
                Console.WriteLine(" >> Failed to {0}. {1}", sqlCmd, ex.Message);
            }
            finally
            {
                _db.Close();
            }
        }

        #endregion

        static void Main(string[] args)
        {
            var runner = new Program();

            runner.CreateDatabase();

            runner.TestInsert();
            runner.TestFind();

            runner.TestUpdate();
            runner.TestFind();

            runner.TestDelete();
            runner.TestFind();

            runner.CloseDatabase();

            Console.ReadLine();
        }
    }

运行输出结果:



三,注意事项

如果你对常用的数据库命令语法还不太了解,可以参考如下链接:

// SQL syntax
//
Select : http://en.wikipedia.org/wiki/Select_(SQL)
Insert : http://en.wikipedia.org/wiki/Insert_(SQL)
Delete : http://en.wikipedia.org/wiki/Delete_(SQL)
Update : http://en.wikipedia.org/wiki/Update_(SQL)
Truncate : http://en.wikipedia.org/wiki/Truncate_(SQL)

由于各个数据库厂商有不同的数据库实现,导致数据库命令语法有一些细微的差别,因此需要特别注意。以下就列出一些常见的不同之处:

1,最大查询记录数

对于 SQL Server 使用 top 关键字。如:

select top 100 * from customer

对于 MySQL 使用 limit 关键字。如:

select * from customer limit 100

对于 Oracle 使用 rownum <=。如:

select * from customer where rownum <= 100

2,命令中出现的转义字符(详见 DatabaseHelper 类的 Validate 方法)

对于 SQL Server,单引号 ' 要用两个单引号 '' 替换;双引号 " 要用两个双引号 "" 替换;

对于 MySQL,单引号 ' 要用 \' 替换;反斜杠 \ 用于 \\ 替换。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值