在上两篇和中,我们开启了C#与Java中的话题之一:相似的方法。其实我写主这两篇文章的目的,有两个:
1、总结自己的学习历程,这个是主要的。
2、给c#转入java的同学一个快速熟悉的感觉,所以这个系列的名称也是“快速煮成”。
因为我对这两门语言仅限了解,对c#也仅限于熟悉,如有理解不妥之处,请指正。
今天我们看看这两种语言环境下纯粹的数据访问。
首先我再次声明:
1、本文不比较这两种语言的数据访问的性能差异。
2、本文不涉及各自的OR框架, 如C#的ADO.NET Entity Framework,MVC,Nhibernate,spring.net,以及Java领域的Spring/Hibernate/Struts等第三方框架,只是纯粹的数据访问。
3、数据库采用MS SQL server 2008,其实也可以用mySQL,MySQL提供官方支持。oracle平时很少用,DB2没用过。
准备工作:一个用于测试的部门表DepartDemo,表结构如下:
Create database Db2010Demogouse Db2010Demogoif exists (select 1from sysobjectswhere id = object_id('DepartDemo')and type = 'U')drop table DepartDemogo/*==============================================================*//* Table: DepartDemo *//*==============================================================*/create table DepartDemo (PKID int identity(101,1),DName nvarchar(200) null,DCode nvarchar(500) null,Manager nvarchar(50) null,ParentID int null default 0,AddUser nvarchar(50) null,AddTime datetime null,ModUser nvarchar(50) null,ModTime datetime null,CurState smallint not null default 0,Remark nvarchar(500) null,F1 int not null default 0,F2 nvarchar(300) null,constraint PK_DEPARTDEMO primary key (PKID))go--插入一条测试数据insert into DepartDemoselect '国家统计局房产审计一科','0','胡不归',0,'DeomUser',getdate(),'','1900-01-01',1,'专业评估全国房价,为老百姓谋福祉',0,''--创建一个存储过程,在C#程序中用到IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[DepartDemoSelectByPKID]') AND type='P')DROP PROCEDURE [dbo].[DepartDemoSelectByPKID]GOCREATE PROCEDURE [dbo].[DepartDemoSelectByPKID](@Pkid int)ASBEGIN TRANSelect * From [DepartDemo] Where [Pkid]=@PkidIF @@ERROR!=0BEGINROLLBACKENDELSEBEGINCOMMITENDGO
一、我们看看C#环境下一个数据访问的简单例子。
在vs2010中新建一控制台项目,结构如下:
相应的代码,
基础数据层:
Database.cs:
- using System;
- using System.Collections.Generic;
- using System.Text;
- using System.Data;
- using System.Data.SqlClient;
- namespace demo2010.database
- {
- public class DataBase
- {
- private static string connectionString = System.Configuration.ConfigurationManager.AppSettings["GlobalsConnString"];
- public static string ConnectionString
- {
- get { return connectionString; }
- set { connectionString = value; }
- }
- #region Helpers
- internal protected static IDataReader GetReader(string commandText, SqlParameter[] p)
- {
- return SqlHelper.ExecuteReader(ConnectionString, CommandType.StoredProcedure, commandText, p);
- }
- internal protected static IDataReader GetReader(string commandText)
- {
- return SqlHelper.ExecuteReader(ConnectionString, CommandType.StoredProcedure, commandText);
- }
- internal protected static int NonQueryInt(string commandText, SqlParameter[] p)
- {
- return SqlHelper.ExecuteNonQuery(ConnectionString, CommandType.StoredProcedure, commandText, p);
- }
- internal protected static bool NonQueryBool(string commandText, SqlParameter[] p)
- {
- return NonQueryInt(commandText, p) > 0;
- }
- internal protected void RunSql(string commandText)
- {
- SqlHelper.ExecuteNonQuery(ConnectionString, CommandType.Text, commandText);
- }
- public static void ExecuteSQL(string commandText)
- {
- SqlHelper.ExecuteNonQuery(ConnectionString, CommandType.Text, commandText);
- }
- public static DataTable GetDataTable(string commandText)
- {
- return SqlHelper.ExecuteDataTable(ConnectionString, CommandType.Text, commandText);
- }
- public static DataTable GetDataTable(string commandText, CommandType commandType)
- {
- return SqlHelper.ExecuteDataTable(ConnectionString, commandType, commandText);
- }
-
- internal protected static string ReturnString(string commandText, SqlParameter[] p)
- {
- object result = SqlHelper.ExecuteScalar(ConnectionString, System.Data.CommandType.StoredProcedure, commandText, p);
- return result.ToString();
- }
- internal protected static SqlParameter ReTurnStringValue
- {
- get
- {
- return SqlHelper.MakeOutParam("@ReTurnValue", SqlDbType.NVarChar, 200);
- }
- }
- internal protected static SqlParameter ReTurnLongValue
- {
- get
- {
- return SqlHelper.MakeOutParam("@ReTurnValue", SqlDbType.BigInt, 8);
- }
- }
- #endregion
- }
- }
using System;using System.Collections.Generic;using System.Text;using System.Data;using System.Data.SqlClient;namespace demo2010.database{ public class DataBase { private static string connectionString = System.Configuration.ConfigurationManager.AppSettings["GlobalsConnString"]; public static string ConnectionString { get { return connectionString; } set { connectionString = value; } } #region Helpers internal protected static IDataReader GetReader(string commandText, SqlParameter[] p) { return SqlHelper.ExecuteReader(ConnectionString, CommandType.StoredProcedure, commandText, p); } internal protected static IDataReader GetReader(string commandText) { return SqlHelper.ExecuteReader(ConnectionString, CommandType.StoredProcedure, commandText); } internal protected static int NonQueryInt(string commandText, SqlParameter[] p) { return SqlHelper.ExecuteNonQuery(ConnectionString, CommandType.StoredProcedure, commandText, p); } internal protected static bool NonQueryBool(string commandText, SqlParameter[] p) { return NonQueryInt(commandText, p) > 0; } internal protected void RunSql(string commandText) { SqlHelper.ExecuteNonQuery(ConnectionString, CommandType.Text, commandText); } public static void ExecuteSQL(string commandText) { SqlHelper.ExecuteNonQuery(ConnectionString, CommandType.Text, commandText); } public static DataTable GetDataTable(string commandText) { return SqlHelper.ExecuteDataTable(ConnectionString, CommandType.Text, commandText); } public static DataTable GetDataTable(string commandText, CommandType commandType) { return SqlHelper.ExecuteDataTable(ConnectionString, commandType, commandText); } internal protected static string ReturnString(string commandText, SqlParameter[] p) { object result = SqlHelper.ExecuteScalar(ConnectionString, System.Data.CommandType.StoredProcedure, commandText, p); return result.ToString(); } internal protected static SqlParameter ReTurnStringValue { get { return SqlHelper.MakeOutParam("@ReTurnValue", SqlDbType.NVarChar, 200); } } internal protected static SqlParameter ReTurnLongValue { get { return SqlHelper.MakeOutParam("@ReTurnValue", SqlDbType.BigInt, 8); } } #endregion }}
DynamicBuilder.cs:
- using System;
- using System.Collections.Generic;
- using System.Data.SqlClient;
- using System.Reflection;
- using System.Reflection.Emit;
- using System.Data;
- namespace demo2010.database
- {
-
-
-
-
- public class DynamicBuilder<T>
- {
- private static readonly MethodInfo getValueMethod = typeof(IDataRecord).GetMethod("get_Item", new Type[] { typeof(int) });
- private static readonly MethodInfo isDBNullMethod = typeof(IDataRecord).GetMethod("IsDBNull", new Type[] { typeof(int) });
- private delegate T Load(IDataRecord dataRecord);
- private const BindingFlags BINDING_FLAGS = BindingFlags.Instance | BindingFlags.Public | BindingFlags.IgnoreCase;
- private Load handler;
- private DynamicBuilder() { }
- public T Build(IDataRecord dataRecord)
- {
- return handler(dataRecord);
- }
- public static DynamicBuilder<T> CreateBuilder(IDataRecord dataRecord)
- {
- DynamicBuilder<T> dynamicBuilder = new DynamicBuilder<T>();
- DynamicMethod method = new DynamicMethod("DynamicCreate", typeof(T), new Type[] { typeof(IDataRecord) }, typeof(T), true);
- ILGenerator generator = method.GetILGenerator();
- LocalBuilder result = generator.DeclareLocal(typeof(T));
- generator.Emit(OpCodes.Newobj, typeof(T).GetConstructor(Type.EmptyTypes));
- generator.Emit(OpCodes.Stloc, result);
- for (int i = 0; i < dataRecord.FieldCount; i++)
- {
- PropertyInfo propertyInfo = typeof(T).GetProperty(dataRecord.GetName(i),BINDING_FLAGS);
- Label endIfLabel = generator.DefineLabel();
- if (propertyInfo != null && propertyInfo.GetSetMethod() != null)
- {
- generator.Emit(OpCodes.Ldarg_0);
- generator.Emit(OpCodes.Ldc_I4, i);
- generator.Emit(OpCodes.Callvirt, isDBNullMethod);
- generator.Emit(OpCodes.Brtrue, endIfLabel);
- generator.Emit(OpCodes.Ldloc, result);
- generator.Emit(OpCodes.Ldarg_0);
- generator.Emit(OpCodes.Ldc_I4, i);
- generator.Emit(OpCodes.Callvirt, getValueMethod);
- generator.Emit(OpCodes.Unbox_Any, dataRecord.GetFieldType(i));
- generator.Emit(OpCodes.Callvirt, propertyInfo.GetSetMethod());
- generator.MarkLabel(endIfLabel);
- }
- }
- generator.Emit(OpCodes.Ldloc, result);
- generator.Emit(OpCodes.Ret);
- dynamicBuilder.handler = (Load)method.CreateDelegate(typeof(Load));
- return dynamicBuilder;
- }
- }
- }
using System;using System.Collections.Generic;using System.Data.SqlClient;using System.Reflection;using System.Reflection.Emit;using System.Data;namespace demo2010.database{ /// <summary> /// Tony 2008.8.28 Add /// </summary> /// <typeparam name="T"></typeparam> public class DynamicBuilder<T> { private static readonly MethodInfo getValueMethod = typeof(IDataRecord).GetMethod("get_Item", new Type[] { typeof(int) }); private static readonly MethodInfo isDBNullMethod = typeof(IDataRecord).GetMethod("IsDBNull", new Type[] { typeof(int) }); private delegate T Load(IDataRecord dataRecord); private const BindingFlags BINDING_FLAGS = BindingFlags.Instance | BindingFlags.Public | BindingFlags.IgnoreCase;//Added by Tony 2008.09.25 private Load handler; private DynamicBuilder() { } public T Build(IDataRecord dataRecord) { return handler(dataRecord); } public static DynamicBuilder<T> CreateBuilder(IDataRecord dataRecord) { DynamicBuilder<T> dynamicBuilder = new DynamicBuilder<T>(); DynamicMethod method = new DynamicMethod("DynamicCreate", typeof(T), new Type[] { typeof(IDataRecord) }, typeof(T), true); ILGenerator generator = method.GetILGenerator(); LocalBuilder result = generator.DeclareLocal(typeof(T)); generator.Emit(OpCodes.Newobj, typeof(T).GetConstructor(Type.EmptyTypes)); generator.Emit(OpCodes.Stloc, result); for (int i = 0; i < dataRecord.FieldCount; i++) { PropertyInfo propertyInfo = typeof(T).GetProperty(dataRecord.GetName(i),BINDING_FLAGS);//performance'Maxvalue decrease 5% **** Test By Tony 2008.09.25 Label endIfLabel = generator.DefineLabel(); if (propertyInfo != null && propertyInfo.GetSetMethod() != null) { generator.Emit(OpCodes.Ldarg_0); generator.Emit(OpCodes.Ldc_I4, i); generator.Emit(OpCodes.Callvirt, isDBNullMethod); generator.Emit(OpCodes.Brtrue, endIfLabel); generator.Emit(OpCodes.Ldloc, result); generator.Emit(OpCodes.Ldarg_0); generator.Emit(OpCodes.Ldc_I4, i); generator.Emit(OpCodes.Callvirt, getValueMethod); generator.Emit(OpCodes.Unbox_Any, dataRecord.GetFieldType(i)); generator.Emit(OpCodes.Callvirt, propertyInfo.GetSetMethod()); generator.MarkLabel(endIfLabel); } } generator.Emit(OpCodes.Ldloc, result); generator.Emit(OpCodes.Ret); dynamicBuilder.handler = (Load)method.CreateDelegate(typeof(Load)); return dynamicBuilder; } }}
SqlHelper.cs:(我们将最常用的SQL在大家熟悉的SqlHelper中。)
- using System;
- using System.Configuration;
- using System.Data;
- using System.Xml;
- using System.Data.SqlClient;
- using System.Collections;
- namespace demo2010.database
- {
- #region Disclaimer/Info
- #endregion
-
-
-
-
- public sealed class SqlHelper
- {
- #region private utility methods & constructors
-
-
- private SqlHelper() { }
-
-
-
-
-
-
-
-
-
-
-
-
- private static void AttachParameters(SqlCommand command, SqlParameter[] commandParameters)
- {
- foreach (SqlParameter p in commandParameters)
- {
-
- if ((p.Direction == ParameterDirection.InputOutput) && (p.Value == null))
- {
- p.Value = DBNull.Value;
- }
- command.Parameters.Add(p);
- }
- }
-
-
-
-
-
- private static void AssignParameterValues(SqlParameter[] commandParameters, object[] parameterValues)
- {
- if ((commandParameters == null) || (parameterValues == null))
- {
-
- return;
- }
-
- if (commandParameters.Length != parameterValues.Length)
- {
- throw new ArgumentException("Parameter count does not match Parameter Value count.");
- }
-
-
- for (int i = 0, j = commandParameters.Length; i < j; i++)
- {
- commandParameters[i].Value = parameterValues[i];
- }
- }
-
-
-
-
-
-
-
-
-
-
- private static void PrepareCommand(SqlCommand command, SqlConnection connection, SqlTransaction transaction, CommandType commandType, string commandText, SqlParameter[] commandParameters)
- {
-
- if (connection.State != ConnectionState.Open)
- {
- connection.Open();
- }
-
- command.Connection = connection;
-
- command.CommandText = commandText;
-
- if (transaction != null)
- {
- command.Transaction = transaction;
- }
-
- command.CommandType = commandType;
-
- if (commandParameters != null)
- {
- AttachParameters(command, commandParameters);
- }
- return;
- }
- #endregion private utility methods & constructors
- #region DataHelpers
- public static string CheckNull(object obj)
- {
- return (string)obj;
- }
- public static string CheckNull(DBNull obj)
- {
- return null;
- }
- #endregion
- #region AddParameters
- public static object CheckForNullString(string text)
- {
- if (text == null || text.Trim().Length == 0)
- {
- return string.Empty;
-
- }
- else
- {
- return text;
- }
- }
- public static object CheckForNullDateTime(object obj)
- {
- if (obj == null)
- {
- return Convert.ToDateTime("1900-01-01");
-
- }
- else
- {
- return obj;
- }
- }
- public static SqlParameter MakeInParam(string ParamName, object Value)
- {
- return new SqlParameter(ParamName, Value);
- }
-
-
-
-
-
-
-
-
- public static SqlParameter MakeInParam(string ParamName, SqlDbType DbType, int Size, object Value)
- {
- return MakeParam(ParamName, DbType, Size, ParameterDirection.Input, Value);
- }
-
-
-
-
-
-
-
- public static SqlParameter MakeOutParam(string ParamName, SqlDbType DbType, int Size)
- {
- return MakeParam(ParamName, DbType, Size, ParameterDirection.Output, null);
- }
-
-
-
-
-
-
-
-
-
- public static SqlParameter MakeParam(string ParamName, SqlDbType DbType, Int32 Size, ParameterDirection Direction, object Value)
- {
- SqlParameter param;
- if (Size > 0)
- param = new SqlParameter(ParamName, DbType, Size);
- else
- param = new SqlParameter(ParamName, DbType);
- param.Direction = Direction;
- if (!(Direction == ParameterDirection.Output && Value == null))
- param.Value = Value;
- return param;
- }
- #endregion
- #region ExecuteNonQuery
-
-
-
-
-
-
-
-
-
-
-
-
- public static int ExecuteNonQuery(string connectionString, CommandType commandType, string commandText)
- {
-
- return ExecuteNonQuery(connectionString, commandType, commandText, (SqlParameter[])null);
- }
-
-
-
-
-
-
-
-
-
-
-
-
-
- public static int ExecuteNonQuery(string connectionString, CommandType commandType, string commandText, params SqlParameter[] commandParameters)
- {
-
- using (SqlConnection cn = new SqlConnection(connectionString))
- {
- cn.Open();
-
- return ExecuteNonQuery(cn, commandType, commandText, commandParameters);
- }
- }
-
-
-
-
-
-
-
-
-
-
-
- public static int ExecuteNonQuery(SqlConnection connection, CommandType commandType, string commandText)
- {
-
- return ExecuteNonQuery(connection, commandType, commandText, (SqlParameter[])null);
- }
-
-
-
-
-
-
-
-
-
-
-
-
-
- public static int ExecuteNonQuery(SqlConnection connection, CommandType commandType, string commandText, params SqlParameter[] commandParameters)
- {
-
- SqlCommand cmd = new SqlCommand();
- PrepareCommand(cmd, connection, (SqlTransaction)null, commandType, commandText, commandParameters);
-
- int retval = cmd.ExecuteNonQuery();
-
- cmd.Parameters.Clear();
- return retval;
- }
-
-
-
-
-
-
-
-
-
-
-
- public static int ExecuteNonQuery(SqlTransaction transaction, CommandType commandType, string commandText)
- {
-
- return ExecuteNonQuery(transaction, commandType, commandText, (SqlParameter[])null);
- }
-
-
-
-
-
-
-
-
-
-
-
-
-
- public static int ExecuteNonQuery(SqlTransaction transaction, C
给我老师的人工智能教程打call!