我记录ORM的几个优点——
1)同时支持多种数据库;
2)速度快:内置透明缓存机制,只要内存足够,大多数时候,速度超过原生的sql查询;
3)使用简单;
4)面向对象的思维模式。
但是,ORM仍然有一些缺点,无法代替关系型数据库的全部功能。有些复杂的关联、统计等查询,建议你直接使用sql语句。
wojilu ORM 抽象了数据层,让你不用操心数据库连接,甚至大多数时候不用操心多个数据库之间的差别,就能极其简单的运行sql语句。
从这个意义上讲,你就是把 wojilu ORM 当做第三方数据组件使用,也是极其方便的。
比如:
IDataReader myreader = db.RunReader<T>
Object ret= db.RunScalar<T>
void db.RunSql<T>
DataTable table= db.RunTable<T>
注意,上面4个方法都带一个泛型T,主要是用于多数据库场合。根据这个T,框架可以正确判断你的数据在哪个数据库。
在wojilu框架2.0中,也可以不使用泛型参数T,那么表示在默认数据库上查询:
IDataReader myreader = db.RunReader
Object ret= db.RunScalar
void db.RunSql
DataTable ret= db.RunTable
【除此之外,你也可以直接使用connection,command运行sql】
框架1.9为了更加方便执行自定义sql语句,给db类增加了几个快捷方式:
1) 获取数据库 connection。需要自己Open和Close
IDbConnection cn1 = db.getConnection(); // 获取默认数据库的connection
IDbConnection cn2 = db.getConnection( "mydb" ); // 获取orm.config配置中,名叫“mydb”的数据库的connection
IDbConnection cn3 = db.getConnection( typeof(BlogPost) ); // 根据实体类型,获取它所在的数据库连接
2) 获取数据库 command,然后可以执行
IDbCommand cmd1 = db.getCommand( "select * from xxx where xxx" ); // 获取默认数据库的command
IDbCommand cmd2 = db.getCommand( "dbName", "select * from xxx where xxx" ); // 第一个参数是数据库名称
IDbCommand cmd3 = db.getCommand( someConnection, "select * from xxx where xxx" ); // 第一个参数是数据库connection
IDbCommand cmd4 = db.getCommand( typeof(BlogPost), "select * from xxx where xxx" ); // 根据类型,执行sql
有了 command,你就可以直接执行sql语句了,比如
IDataReader rd = cmd.ExecuteReader();
3) 获取数据库connection string
String str1 = db.getConnectionString(); // 获取默认数据库的 connection string
String str2 = db.getConnectionString( "dbName" ); // 根据数据库名称获取 connection string
4) 获取数据库类型
String str1 = db.getDatabaseType(); // 获取 orm.config 中DbType配置项中的数据库类型
String str2 = db.getDatabaseType( "dbName" ); 根据数据库名称获取数据库类型