在我们写程序的时候,特别是数据库应用程序的时候,经常会遇到这样的情况:对于一个给定的表,写出这个表对应的类(用一句时髦的话说是实现业务实体类),类的数据成员是所有的字段,并且类含有该表的添加修改删除等操作。还有,对于一个给定的存储过程,要完成根据存储过程存取数据或别的数据库操作。如下代码就是我们通常要完成的: 1.表的业务实体化 private int iId ; public int Id { get { return iId ; } set { iId = value ; } }
private string strName ; public string Name { get { return strName ; } set { strName = value ; } }
private string strCode ; public string Code { get { return strCode ; } set { strCode = value ; } }
private string strDescription ; public string Description { get { return strDescription ; } set { strDescription = value ; } }
private int iFatherid ; public int Fatherid { get { return iFatherid ; } set { iFatherid = value ; } }
private int iType ; public int Type { get { return iType ; } set { iType = value ; } }
private int iUserId ; public int UserId { get { return iUserId ; } set { iUserId = value ; } }
ublic bool Add() { SqlConnection conn = SqlConn.Instance().Connection ;
string strSql = "insert into book(id, Name, Code, Description, Fatherid, Type, UserId)" +"values(@id, @Name, @Code, @Description, @Fatherid, @Type, @UserId)" ;
SqlCommand command = new SqlCommand(strSql,conn) ;
command.Parameters.Add("@id",SqlDbType.Int ) ; command.Parameters["@id"].value = iId ;
command.Parameters.Add("@Name",SqlDbType.NVarChar ,50) ; if (strName!= null ) command.Parameters["@Name"].value = strName ; else command.Parameters["@Name"].value = DBNull.value ;
command.Parameters.Add("@Code",SqlDbType.NVarChar ,255) ; if (strCode!= null ) command.Parameters["@Code"].value = strCode ; else command.Parameters["@Code"].value = DBNull.value ;
command.Parameters.Add("@Description",SqlDbType.NVarChar ,255) ; if (strDescription!= null ) command.Parameters["@Description"].value = strDescription ; else command.Parameters["@Description"].value = DBNull.value ;
command.Parameters.Add("@Fatherid",SqlDbType.Int ) ; command.Parameters["@Fatherid"].value = iFatherid ;
command.Parameters.Add("@Type",SqlDbType.Int ) ; command.Parameters["@Type"].value = iType ;
command.Parameters.Add("@UserId",SqlDbType.Int ) ; command.Parameters["@UserId"].value = iUserId ;
try { conn.Open() ; command.ExecuteNonQuery() ; return true ; } catch(Exception e) { throw(new Exception("Error in the Database"+e.Message)) ; } finally { conn.Close() ; } } public bool Modify() { SqlConnection conn = SqlConn.Instance().Connection ; string strSql ="update book set id = @id, Name = @Name, Code = @Code, Description = @Description, Fatherid = @Fatherid, Type = @Type, UserId = @UserId " + " where id =@id " ; SqlCommand command = new SqlCommand(strSql,conn) ; command.Parameters.Add("@id",SqlDbType.Int ) ; command.Parameters["@id"].value = iId ;
command.Parameters.Add("@Name",SqlDbType.NVarChar ,50) ; command.Parameters["@Name"].value = strName ;
command.Parameters.Add("@Code",SqlDbType.NVarChar ,255) ; command.Parameters["@Code"].value = strCode ;
command.Parameters.Add("@Description",SqlDbType.NVarChar ,255) ; command.Parameters["@Description"].value = strDescription ;
command.Parameters.Add("@Fatherid",SqlDbType.Int ) ; command.Parameters["@Fatherid"].value = iFatherid ;
command.Parameters.Add("@Type",SqlDbType.Int ) ; command.Parameters["@Type"].value = iType ;
command.Parameters.Add("@UserId",SqlDbType.Int ) ; command.Parameters["@UserId"].value = iUserId ;
try { conn.Open() ; command.ExecuteNonQuery() ; return true ; } catch(Exception e) { throw(new Exception("Error in the Database"+e.Message)) ; } finally { conn.Close() ; } }
再看一下存储过程: public bool ExeSP_ddms_Modify_Trx( int aiPrsn_trx_no, int aiUlt_incid_no, int aiPrsn_trx_status_cd, DateTime adtTrx_cmpl_dt, string astrEmail_addr) { SqlConnection conn = SqlConn.Instance().Connection ;
string strSPName = "ddms_Modify_Trx" ; SqlCommand command = new SqlCommand(strSPName,conn) ; command.CommandType = CommandType.StoredProcedure ;
command.Parameters.Add("@prsn_trx_no",SqlDbType.SmallInt ) ; command.Parameters["@prsn_trx_no"].value= aiPrsn_trx_no ;
command.Parameters.Add("@ult_incid_no",SqlDbType.Int ) ; command.Parameters["@ult_incid_no"].value= aiUlt_incid_no ;
command.Parameters.Add("@prsn_trx_status_cd",SqlDbType.Int ) ; command.Parameters["@prsn_trx_status_cd"].value= aiPrsn_trx_status_cd ;
command.Parameters.Add("@trx_cmpl_dt",SqlDbType.DateTime ) ; if ( adtTrx_cmpl_dt!= DateTime.Minvalue ) command.Parameters["@trx_cmpl_dt"].value= adtTrx_cmpl_dt ; else command.Parameters["@trx_cmpl_dt"].value= DBNull.value ;
command.Parameters.Add("@email_addr",SqlDbType.VarChar ,70) ; if ( astrEmail_addr!= null ) command.Parameters["@email_addr"].value= astrEmail_addr ; else command.Parameters["@email_addr"].value= DBNull.value ;
try { conn.Open() ; command.ExecuteNonQuery() ; return true ; } catch(Exception e) { throw(new Exception("Error in the Database"+e.Message)) ; } finally { conn.Close() ; } }
上面处理表的代码也挺长的,但那只是7个字段,如果一个表含有二三十个字段的话,恐怕代码更长,同样,检查你写好的代码是否有错误也是一个痛苦的过程。 但是,写这些代码本身并没有多少难度,而且很多工作都是重复的,这就不能不启发我们通过一个程序来完成这些繁琐易出错的工作。 假如让我们来设计一个程序完成上面的代码,我们应该怎么做哪?
要完成上面的工作,我们首先应该找到我们要处理的表或存储过程。 我们也可以通过编程实现: 1.列出所有的数据库服务器 public static ArrayList GetServerList() { ArrayList alServers = new ArrayList() ; SQLDMO.Application sqlApp = new SQLDMO.ApplicationClass() ; try { SQLDMO.NameList serverList = sqlApp.ListAvailableSQLServers() ; for(int i = 1;i<= serverList.Count;i++) { alServers.Add(serverList.Item(i)) ; } } catch(Exception e) { throw(new Exception("取数据库服务器列表出错:"+e.Message)) ; } finally { sqlApp.Quit() ; } return alServers ; } 这样,所有的数据库服务器迷宫凝成都存在了ArrayList里,我们可以用一个下拉列表来列出所有的服务器,让用户选择他需要的一个。 2。得到选定服务器所有的数据库列表 要完成这个工作,我们需要用户输入这个数据库服务器的用户名和密码,代码如下: public static ArrayList GetDbList(string strServerName,string strUserName,string strPwd) { ArrayList alDbs = new ArrayList() ; SQLDMO.Application sqlApp = new SQLDMO.ApplicationClass() ; SQLDMO.SQLServer svr = new SQLDMO.SQLServerClass() ; try { svr.Connect(strServerName,strUserName,strPwd) ; foreach(SQLDMO.Database db in svr.Databases) { if(db.Name!=null) alDbs.Add(db.Name) ; } } catch(Exception e) { throw(new Exception("连接数据库出错:"+e.Message)) ; } finally { svr.DisConnect() ; sqlApp.Quit() ; } return alDbs ; } 这样就得到了数据库的列表,你同样可以让用户选择一个数据库。 3。列出选定数据库所有的用户表和存储过程 在这一步我们不用SQLDMO了,我们通过读取选定数据库的sysobjects表中的记录实现,当然,完成这个工作需要如下信息:你选择的数据库服务器名,用户名,密码,数据库名等信息: public static ArrayList GetTableList(string strServerName,string strDBName,string strUserName,string strPwd) { string strConStr = " data source="+ strServerName +";initial catalog="+strDBName + ";password="+ strPwd+";persist security info=True;user id="+ strUserName; SqlConnection conn = new SqlConnection(strConStr) ;
ArrayList alTbs = new ArrayList() ;
string strSql = "select * from sysobjects where (xtype='u' or xtype='p') and category<>2 order by name" ; SqlCommand comm = new SqlCommand(strSql,conn) ;
SqlDataReader sr = null ; try { conn.Open() ; sr = comm.ExecuteReader() ; while(sr.Read()) { string strName = sr["name"].ToString() ; bool blTable = sr["xtype"].ToString().Trim().ToUpper() == "U"?true:false ; TableInfo tb = new TableInfo(strName,blTable) ; alTbs.Add(tb) ; }
} catch(Exception err) { throw(new Exception("取表明列表出错:"+err.Message)) ; } finally { if (sr != null) { sr.Close() ; sr = null ; } conn.Close() ; } return alTbs ; } 这样我们就得到了所有的用户表和存储过程,注意这一句: select * from sysobjects where (xtype='u' or xtype='p') and category<>2 order by name,这是关键的sql语句,其中xtype='u' 表示用户表,xtype='p'表示存储过程,category<>2表示不是系统存储过程。
下一步是取得选定表的所有字段或存储过程的所有参数 我们从表syscolumns取得我们想要到的东西: strTableName = tbInfo.Name ; string strSql = "select * from syscolumns where id=( " + " select id from sysobjects where name='"+ strTableName + "')" ;
SqlDataAdapter sa = new SqlDataAdapter(strSql,conn) ; DataSet ds = new DataSet() ; sa.Fill(ds) ; 这样我们就把某个表(或存储过程)的所有字段信息放到了结果集ds里。 在syscolumns 里有一个字段xtype,该字段表示列的数据类型,俺定义了两个函数,能根据xtype的值得到对应的dotnet中的数据类型和sqldb数据类型: private string getType(int iType) { string strResult = "" ; switch(iType) { case 34: strResult = "Byte[]" ; break ; case 35: case 99: case 167: case 175: case 231: case 239: strResult = "string" ; break ; case 48: case 52: case 56: case 127: strResult = "int" ; break ; case 58: case 61: strResult = "DateTime" ; break ; case 59: strResult = "Single" ; break ; case 60: case 106: case 108: case 122: strResult = "Decimal" ; break ; case 62: strResult = "Double" ; break ; case 104: strResult = "bool" ; break ; default: strResult = "None" ;//"unknow" ; break ; } return strResult + " " ; }
private string getSqlDBType(int iType) { string strResult = "" ; switch(iType) { case 34: strResult = "SqlDbType.Image" ; break ; case 35: strResult = "SqlDbType.Text" ; break ; case 48: strResult = "SqlDbType.TinyInt" ; break ; case 52: strResult = "SqlDbType.SmallInt" ; break ; case 56: strResult = "SqlDbType.Int" ; break ; case 58: strResult = "SqlDbType.SmallDateTime" ; break ; case 59: strResult = "SqlDbType.Real" ; break ; case 60: strResult = "SqlDbType.Money" ; break ; case 61: strResult = "SqlDbType.DateTime" ; break ; case 62: strResult = "SqlDbType.Float" ; break ; case 99: strResult = "SqlDbType.NText" ; break ; case 104: strResult = "SqlDbType.Bit" ; break ; case 106: strResult = "SqlDbType.Decimal" ; break ; case 108: strResult = "SqlDbType.Decimal" ; break ; case 122: strResult = "SqlDbType.SmallMoney" ; break ; case 127: strResult = "SqlDbType.BigInt" ; break ; case 165: strResult = "SqlDbType.VarBinary" ; break ; case 167: strResult = "SqlDbType.VarChar" ; break ; case 173: strResult = "SqlDbType.Binary" ; break ; case 175: strResult = "SqlDbType.Char" ; break ; case 189: strResult = "SqlDbType.Timestamp" ; break ; case 231: strResult = "SqlDbType.NVarChar" ; break ; case 239: strResult = "SqlDbType.NChar" ; break ; default: strResult = "None" ;//"unknow" ; break ; } return strResult + " " ; } 当然,还有一个函数先介绍一下,后面有它的具体用法: private string getTypeShort(int iType) { string strResult = "" ; switch(getType(iType).Trim()) { case "Byte[]": strResult = "img" ; break ; case "string": strResult = "str" ; break ; case "int": strResult = "i" ; break ; case "DateTime": strResult = "dt" ; break ; case "Single": strResult = "sig" ; break ; case "Decimal": strResult = "dec" ; break ; case "Double": strResult = "db" ; break ; case "bool": strResult = "bl" ; break ; default: strResult = "unknow" ; break ; } return strResult ; }
现在有了上面的介绍和函数基础,我们可以逐步实现我们的目标了: 1.生成数据实体类的数据成员 大家看一下,对于一个字段id,整形,我们这样定义: private int iId ; public int Id { get { return iId ; } set { iId = value ; } } 其中iId表示数据类型+字段名称,其中字段名称的第一个字母大写,代码实现如下: private string BuildMember(DataSet ds) { StringBuilder sb = new StringBuilder() ; foreach(DataRow dr in ds.Tables[0].Rows) { int iType = (byte)dr["xtype"] ; string strType = getType(iType) ; string strName = dr["name"].ToString() ; strName = UpFirstChar(strName) ; string strShortType = getTypeShort(iType) ; string strPrivateline = "private " + strType + strShortType +strName +" ;\r\n" ; sb.Append(strPrivateline) ; string strPublicline = "public " + strType + strName +" \r\n" ; sb.Append(strPublicline) ; sb.Append("{\r\n") ; sb.Append("\tget\r\n") ; sb.Append("\t{\r\n") ; sb.Append("\t\treturn " +strShortType +strName+ " ;\r\n") ; sb.Append("\t}\r\n") ; sb.Append("\tset\r\n") ; sb.Append("\t{\r\n") ; sb.Append("\t\t" +strShortType +strName+ " = value ;\r\n") ; sb.Append("\t}\r\n") ; sb.Append("}\r\n") ; sb.Append("\r\n") ; sb.Append("\r\n") ; } return sb.ToString(); }
参数DataSet ds中的ds是通过上一页的sa.Fill(ds)得到的,dr["name"]表示字段名称,dr["xtype"] 是字段类型。 UpFirstChar函数负责把字符串的第一个字母大写: private string UpFirstChar(string strvalue) { return strvalue.Substring(0,1).ToUpper() + strvalue.Substring(1,strvalue.Length - 1) ; } 这样就生成了数据实体的数据成员。 2。生成Add方法 Add方法生成起来有点难度,可以参考第一页的程序,我们这里是通过参数的方法来实现add的。有一点要注意,就是在对参数赋值时要考虑参数值为空的情况。代码实现如下: private string BuildAddFunction(DataSet ds) { StringBuilder sb = new StringBuilder() ;
sb.Append("public bool Add()\r\n") ; sb.Append("{\r\n") ; sb.Append("\tSqlConnection conn = SqlConn.Instance().Connection ;\r\n") ; sb.Append("\r\n") ; string strInsert = "\"insert into " + strTableName + "("; string strFiledList = "" ; string strParamList = "" ; foreach(DataRow dr in ds.Tables[0].Rows) { string strName = dr["name"].ToString() ; strFiledList = strFiledList + strName + ", " ; strParamList = strParamList + "@" + strName + ", " ; } strFiledList = strFiledList.Trim().TrimEnd(',') ; strParamList = strParamList.Trim().TrimEnd(',') ; sb.Append("\tstring strSql = " + strInsert + strFiledList+ ")\"\r\n") ; sb.Append("\t+\"values(" + strParamList+ ")\" ;\r\n") ; sb.Append("\r\n") ; sb.Append("\tSqlCommand command = new SqlCommand(strSql,conn) ;\r\n") ; sb.Append("\r\n") ; foreach(DataRow dr in ds.Tables[0].Rows) { string strName = dr["name"].ToString() ; string strSqlType = getSqlDBType((byte)dr["xtype"]) ; string strShortType = getTypeShort((byte)dr["xtype"]) ; string strvalueName = strShortType + UpFirstChar(strName) ; int iLen = (Int16)dr["prec"] ;
string strLen = "" ; if (strShortType == "str") strLen = strLen + "," + iLen ; string strCommandName = "\tcommand.Parameters.Add(\"@" + strName + "\"," + strSqlType + strLen+ ") ;\r\n" ;
string strCommandvalue = "\tcommand.Parameters[\"@" + strName + "\"].value = " + strvalueName + " ;\r\n" ; string strCommandNullvalue = "\tcommand.Parameters[\"@" + strName + "\"].value = DBNull.value ;\r\n" ;
sb.Append(strCommandName) ; if (strShortType == "dt") sb.Append("\tif (" + strvalueName + "!= DateTime.Minvalue )\r\n") ; else if (strShortType == "str") sb.Append("\tif (" + strvalueName + "!= null )\r\n") ; else if (strShortType == "img") sb.Append("\tif (" + strvalueName + "!= null )\r\n") ; else sb.Append("") ; sb.Append(strCommandvalue) ; if (strShortType == "dt" ||strShortType == "str"||strShortType == "img") { sb.Append("\telse\r\n") ; sb.Append(strCommandNullvalue) ; } sb.Append("\r\n") ; }
sb.Append(AddCatchString()) ;
sb.Append("}\r\n") ; return sb.ToString(); }
3。edit,delete的实现方法类似与add,就不详细说了,edit方法代码如下: private string BuildModifyFunction(DataSet ds) { StringBuilder sb = new StringBuilder() ;
sb.Append("public bool Modify()\r\n") ; sb.Append("{\r\n") ; sb.Append("\tSqlConnection conn = SqlConn.Instance().Connection ;\r\n") ; string strModify = "string strSql =\"update " + strTableName + " set ";
string strParamList = "" ; foreach(DataRow dr in ds.Tables[0].Rows) { string strName = dr["name"].ToString() ; strParamList = strParamList + strName + " = @" + strName + ", " ; } strParamList = strParamList.Trim().TrimEnd(',') ; sb.Append("\t" + strModify + strParamList + " \"\r\n") ; sb.Append("\t+ \" where id =@id \" ;\r\n") ;
sb.Append("\tSqlCommand command = new SqlCommand(strSql,conn) ;\r\n") ;
foreach(DataRow dr in ds.Tables[0].Rows) { string strName = dr["name"].ToString() ; string strSqlType = getSqlDBType((byte)dr["xtype"]) ; string strShortType = getTypeShort((byte)dr["xtype"]) ; string strvalueName = strShortType + UpFirstChar(strName) ; int iLen = (Int16)dr["prec"] ;
string strLen = "" ; if (strShortType == "str") strLen = strLen + "," + iLen ;
string strCommandName = "\tcommand.Parameters.Add(\"@" + strName + "\"," + strSqlType + strLen + ") ;\r\n" ; string strCommandvalue = "\tcommand.Parameters[\"@" + strName + "\"].value = " + strvalueName + " ;\r\n" ; sb.Append(strCommandName) ; sb.Append(strCommandvalue) ; sb.Append("\r\n") ; }
sb.Append(AddCatchString()) ;
sb.Append("}\r\n") ; return sb.ToString(); }
4。生成存储过程的执行方法和返回结果方法。存储过程的参数也在syscolumns表里有详细的说明,里面还记录了每个参数是不是传出参数,不过在这个函数里我没有考虑参数的方向,当然,要考虑进去也不是很麻烦。 private string BuildSPExec(DataSet ds) { StringBuilder sb = new StringBuilder() ; string strFuncParam = "" ;
foreach(DataRow dr in ds.Tables[0].Rows) { int iType = (byte)dr["xtype"] ; string strName = UpFirstChar(dr["name"].ToString().TrimStart('@')) ; string strType = getType(iType) ; string strSqlType = getSqlDBType(iType) ; string strShortType = getTypeShort(iType) ; strFuncParam = strFuncParam + "\r\n\t\t" + strType + " a" + strShortType + strName + ","; } strFuncParam = strFuncParam.TrimEnd(',') ; string strDef = "public bool ExeSP_" + strTableName + "(" + strFuncParam + ")\r\n"; sb.Append(strDef) ; sb.Append("{\r\n") ; sb.Append("\tSqlConnection conn = SqlConn.Instance().Connection ;\r\n") ; sb.Append("\r\n") ; sb.Append("\tstring strSPName = \"" + strTableName + "\" ;\r\n") ; sb.Append("\tSqlCommand command = new SqlCommand(strSPName,conn) ;\r\n"); sb.Append("\tcommand.CommandType = CommandType.StoredProcedure ;\r\n") ; sb.Append("\r\n") ;
foreach(DataRow dr in ds.Tables[0].Rows) { int iType = (byte)dr["xtype"] ; string strParaName = dr["name"].ToString() ; string strName = UpFirstChar(strParaName.TrimStart('@')) ; string strSqlType = getSqlDBType(iType) ; string strShortType = getTypeShort(iType) ; string strvalue = " a" + strShortType + strName ; int iLen = (Int16)dr["prec"] ;
string strLen = "" ; if (strShortType == "str") strLen = strLen + "," + iLen ;
string strCommandAdd = "\tcommand.Parameters.Add(\"" + strParaName + "\"," + strSqlType + strLen + ") ;\r\n"; string strCommandvalue = "\tcommand.Parameters[\"" + strParaName + "\"].value=" + strvalue + " ;\r\n"; string strCommandNull = "\tcommand.Parameters[\"" + strParaName + "\"].value= DBNull.value ;\r\n"; sb.Append(strCommandAdd) ; if (strShortType == "dt") sb.Append("\tif (" + strvalue + "!= DateTime.Minvalue )\r\n\t") ; else if (strShortType == "str") sb.Append("\tif (" + strvalue + "!= null )\r\n\t") ; else if (strShortType == "img") sb.Append("\tif (" + strvalue + "!= null )\r\n\t") ; else sb.Append("") ; sb.Append(strCommandvalue) ; if (strShortType == "dt" ||strShortType == "str"||strShortType == "img") { sb.Append("\telse\r\n\t") ; sb.Append(strCommandNull) ; } sb.Append("\r\n") ; } sb.Append(AddCatchString()) ;
sb.Append("}\r\n") ; return sb.ToString() ; }
对于存储过程生成结果集的函数如下: private string BuildSPGetData(DataSet ds) { StringBuilder sb = new StringBuilder() ; string strFuncParam = "" ;
foreach(DataRow dr in ds.Tables[0].Rows) { int iType = (byte)dr["xtype"] ; string strName = UpFirstChar(dr["name"].ToString().TrimStart('@')) ; string strType = getType(iType) ; string strSqlType = getSqlDBType(iType) ; string strShortType = getTypeShort(iType) ; strFuncParam = strFuncParam + "\r\n\t\t" + strType + " a" + strShortType + strName + ","; } strFuncParam = strFuncParam.TrimEnd(',') ; string strDef = "public DataSet QuerySP_" + strTableName + "(" + strFuncParam + ")\r\n"; sb.Append(strDef) ; sb.Append("{\r\n") ; sb.Append("\tSqlConnection conn = SqlConn.Instance().Connection ;\r\n") ; sb.Append("\r\n") ; sb.Append("\tstring strSPName = \"" + strTableName + "\" ;\r\n") ; sb.Append("\tSqlCommand command = new SqlCommand(strSPName,conn) ;\r\n"); sb.Append("\tcommand.CommandType = CommandType.StoredProcedure ;\r\n") ; sb.Append("\r\n") ;
foreach(DataRow dr in ds.Tables[0].Rows) { int iType = (byte)dr["xtype"] ; string strParaName = dr["name"].ToString() ; string strName = UpFirstChar(strParaName.TrimStart('@')) ; string strSqlType = getSqlDBType(iType) ; string strShortType = getTypeShort(iType) ; string strvalue = " a" + strShortType + strName ; int iLen = (Int16)dr["prec"] ;
string strLen = "" ; if (strShortType == "str") strLen = strLen + "," + iLen ;
string strCommandAdd = "\tcommand.Parameters.Add(\"" + strParaName + "\"," + strSqlType + strLen + ") ;\r\n"; string strCommandvalue = "\tcommand.Parameters[\"" + strParaName + "\"].value=" + strvalue + " ;\r\n"; string strCommandNull = "\tcommand.Parameters[\"" + strParaName + "\"].value= DBNull.value ;\r\n"; sb.Append(strCommandAdd) ; if (strShortType == "dt") sb.Append("\tif (" + strvalue + "!= DateTime.Minvalue )\r\n\t") ; else if (strShortType == "str") sb.Append("\tif (" + strvalue + "!= null )\r\n\t") ; else if (strShortType == "img") sb.Append("\tif (" + strvalue + "!= null )\r\n\t") ; else sb.Append("") ; sb.Append(strCommandvalue) ; if (strShortType == "dt" ||strShortType == "str"||strShortType == "img") { sb.Append("\telse\r\n\t") ; sb.Append(strCommandNull) ; } sb.Append("\r\n") ; }
sb.Append("\tSqlDataAdapter sdaResult = new SqlDataAdapter(command) ;\r\n") ; sb.Append("\tDataSet ds = new DataSet() ;\r\n") ;
sb.Append(AddCatchQueryString()) ;
sb.Append("}\r\n") ; return sb.ToString() ;
} 下面是生成结果集的执行结果: public DataSet QuerySP_ddms_GetBank( int aiPrsn_id) { SqlConnection conn = SqlConn.Instance().Connection ;
string strSPName = "ddms_GetBank" ; SqlCommand command = new SqlCommand(strSPName,conn) ; command.CommandType = CommandType.StoredProcedure ;
command.Parameters.Add("@prsn_id",SqlDbType.Int ) ; command.Parameters["@prsn_id"].value= aiPrsn_id ;
SqlDataAdapter sdaResult = new SqlDataAdapter(command) ; DataSet ds = new DataSet() ; try { sdaResult.Fill(ds) ; } catch(Exception e) { throw(new Exception("Error in the Database"+e.Message)) ; } finally { sdaResult.Dispose() ; } return ds ; }
还有两个函数在程序中用到了,如下所示: private string AddCatchString() { StringBuilder sb = new StringBuilder() ; sb.Append("\ttry\r\n") ; sb.Append("\t{\r\n") ; sb.Append("\t\tconn.Open() ;\r\n") ; sb.Append("\t\tcommand.ExecuteNonQuery() ;\r\n") ; sb.Append("\t\treturn true ;\r\n") ; sb.Append("\t}\r\n") ; sb.Append("\tcatch(Exception e)\r\n") ; sb.Append("\t{\r\n") ; sb.Append("\t\tthrow(new Exception(\"Error in the Database\"+e.Message)) ;\r\n") ; sb.Append("\t}\r\n") ; sb.Append("\tfinally\r\n") ; sb.Append("\t{\r\n") ; sb.Append("\t\tconn.Close() ;\r\n") ; sb.Append("\t}\r\n") ; return sb.ToString() ; }
private string AddCatchQueryString() { StringBuilder sb = new StringBuilder() ; sb.Append("\ttry\r\n") ; sb.Append("\t{\r\n") ; sb.Append("\t\tsdaResult.Fill(ds) ;\r\n") ; sb.Append("\t}\r\n") ; sb.Append("\tcatch(Exception e)\r\n") ; sb.Append("\t{\r\n") ; sb.Append("\t\tthrow(new Exception(\"Error in the Database\"+e.Message)) ;\r\n") ; sb.Append("\t}\r\n") ; sb.Append("\tfinally\r\n") ; sb.Append("\t{\r\n") ; sb.Append("\t\tsdaResult.Dispose() ;\r\n") ; sb.Append("\t}\r\n") ; sb.Append("\treturn ds ;\r\n") ; return sb.ToString() ; }
顺便说一下,文章开头的一段代码就是用这个程序生成的,当然,这种方法还有待完善的地方,希望大家指正。
|