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

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

罗朝辉 (http://www.cnblogs.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 中读取值等。

二,使用示例

示例代码如下:

View Code
   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,单引号 ' 要用 \' 替换;反斜杠 \ 用于 \\ 替换。

 

posted @ 2013-03-27 19:17  飘飘白云  阅读(865)  评论(2编辑  收藏  举报
本博客遵循 Creative Commons License “署名-非商业用途-保持一致”创作共用协议。 与我联系