Java是如何快速煮成C 的 (二) 資料訪問 1
阿新 • • 發佈:2018-11-15
分享一下我老師大神的人工智慧教程!零基礎,通俗易懂!http://blog.csdn.net/jiangjunshow
也歡迎大家轉載本篇文章。分享知識,造福人民,實現我們中華民族偉大復興!
在上兩篇《 Java是如何快速煮成C#的?》(一):相似的方法 和《Java是如何快速煮成C#的?》(一):相似的方法(2) 中,我們開啟了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,表結構如下:
相關的SQL語句:
[ruby] view plain copy print ?
- Create database Db2010Demo
- go
- use Db2010Demo
- go
- if exists (select 1
- from sysobjects
- where id = object_id('DepartDemo')
- and type =
- drop table DepartDemo
- go
- /*==============================================================*/
- /* 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 DepartDemo
- select '國家統計局房產審計一科','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]
- GO
- CREATE PROCEDURE [dbo].[DepartDemoSelectByPKID]
- (
- @Pkid int
- )
- AS
- BEGIN TRAN
- Select * From [DepartDemo] Where [Pkid]=@Pkid
- IF @@ERROR!=0
- BEGIN
- ROLLBACK
- END
- ELSE
- BEGIN
- COMMIT
- END
- GO
一、我們看看C#環境下一個資料訪問的簡單例子。
在vs2010中新建一控制檯專案,結構如下:
相應的程式碼,
基礎資料層:
Database.cs:
[c-sharp] view plain copy print ?- 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:
[c-sharp] view plain copy print ?- 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中。)
[c-sharp] view plain copy print ?- 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
- /// <summary>
- /// The SqlHelper class is intended to encapsulate high performance, scalable best practices for
- /// common uses of SqlClient.
- /// </summary>
- public sealed class SqlHelper
- {
- #region private utility methods & constructors
- //Since this class provides only static methods, make the default constructor private to prevent
- //instances from being created with "new SqlHelper()".
- private SqlHelper() { }
- /// <summary>
- /// This method is used to attach array of SqlParameters to a SqlCommand.
- ///
- /// This method will assign a value of DbNull to any parameter with a direction of
- /// InputOutput and a value of null.
- ///
- /// This behavior will prevent default values from being used, but
- /// this will be the less common case than an intended pure output parameter (derived as InputOutput)
- /// where the user provided no input value.
- /// </summary>
- /// <param name="command">The command to which the parameters will be added</param>
- /// <param name="commandParameters">an array of SqlParameters tho be added to command</param>
- private static void AttachParameters(SqlCommand command, SqlParameter[] commandParameters)
- {
- foreach (SqlParameter p in commandParameters)
- {
- //check for derived output value with no value assigned
- if ((p.Direction == ParameterDirection.InputOutput) && (p.Value == null))
- {
- p.Value = DBNull.Value;
- }
- command.Parameters.Add(p);
- }
- }
- /// <summary>
- /// This method assigns an array of values to an array of SqlParameters.
- /// </summary>
- /// <param name="commandParameters">array of SqlParameters to be assigned values</param>
- /// <param name="parameterValues">array of Components holding the values to be assigned</param>
- private static void AssignParameterValues(SqlParameter[] commandParameters, object[] parameterValues)
- {
- if ((commandParameters == null) || (parameterValues == null))
- {
- //do nothing if we get no data
- return;
- }
- // we must have the same number of values as we pave parameters to put them in
- if (commandParameters.Length != parameterValues.Length)
- {
- throw new ArgumentException("Parameter count does not match Parameter Value count.");
- }
- //iterate through the SqlParameters, assigning the values from the corresponding position in the
- //value array
- for (int i = 0, j = commandParameters.Length; i < j; i++)
- {
- commandParameters[i].Value = parameterValues[i];
- }
- }
- /// <summary>
- /// This method opens (if necessary) and assigns a connection, transaction, command type and parameters
- /// to the provided command.
- /// </summary>
- /// <param name="command">the SqlCommand to be prepared</param>
- /// <param name="connection">a valid SqlConnection, on which to execute this command</param>
- /// <param name="transaction">a valid SqlTransaction, or 'null'</param>
- /// <param name="commandType">the CommandType (stored procedure, text, etc.)</param>
- /// <param name="commandText">the stored procedure name or T-SQL command</param>
- /// <param name="commandParameters">an array of SqlParameters to be associated with the command or 'null' if no parameters are required</param>
- private static void PrepareCommand(SqlCommand command, SqlConnection connection, SqlTransaction transaction, CommandType commandType, string commandText, SqlParameter[] commandParameters)
- {
- //if the provided connection is not open, we will open it
- if (connection.State != ConnectionState.Open)
- {
- connection.Open();
- }
- //associate the connection with the command
- command.Connection = connection;
- //set the command text (stored procedure name or SQL statement)
- command.CommandText = commandText;
- //if we were provided a transaction, assign it.
- if (transaction != null)
- {
- command.Transaction = transaction;
- } &nb