我做的一个SQL -> C# AutoCode
有一次做项目的时候,遇到了一大堆的列表表格要输入,开始做了几个表,结果都是一样的代码,甚是郁闷,索性写了个AutoCode来生成,后来项目做完了,没有怎么碰到这样郁闷的工作,也就把它忘了。今天看到了Wintle同学做了个CodePlua(CodePlus C# 代码生成器 V1.0 推出啦!) ,我才想起我也有个这样的冬冬。
我不是要竞争哈,我是觉得可以讨论一下这种做法在数据库操作中算不算郁闷,我把SQL编程C# Class,按字段对应,然后再程序中完全SQL屏蔽掉了。这种方法不算广义的OR Mapping,因为根本没有严格意义上的Relation嘛。不过这样操作数据库表非常的方便,特别是以行为单位操作的时候,SQL的字段完全可以在程序中IntelliSence,编程比较爽哈。
示例代码(SQL):
create table [TableDemo](
ID int identity(1,1),
FieldA nvarchar(50),
FieldB ntext,
FieldC datetime,
FieldD decimal)
ID int identity(1,1),
FieldA nvarchar(50),
FieldB ntext,
FieldC datetime,
FieldD decimal)
C# Class:
/**//// <summary>
/// Automatically Code for Table 'TableDemo',
/// by Birdshome AutoCode Engine V.1.0
/// Copyright (C) 2004.1 Birdshome, HIT
/// </summary>
TableDemo Class#region TableDemo Class
public class TableDemo
{
private System.Int32 m_ID;
private System.String m_FieldA;
private System.String m_FieldB;
private System.DateTime m_FieldC;
private System.Decimal m_FieldD;
private System.Data.SqlClient.SqlCommand SqlCmd;
private bool bSetFieldA = false;
private bool bSetFieldB = false;
private bool bSetFieldC = false;
private bool bSetFieldD = false;
private static string _TableName = "TableDemo";
public System.Int32 ID
{
get
{
return m_ID;
}
}
public System.String FieldA
{
get
{
return m_FieldA;
}
set
{
if ( value != null && m_FieldA != value )
{
m_FieldA = value;
bSetFieldA = true;
}
}
}
public System.String FieldB
{
get
{
return m_FieldB;
}
set
{
if ( value != null && m_FieldB != value )
{
m_FieldB = value;
bSetFieldB = true;
}
}
}
public System.DateTime FieldC
{
get
{
return m_FieldC;
}
set
{
m_FieldC = value;
bSetFieldC = true;
}
}
public System.Decimal FieldD
{
get
{
return m_FieldD;
}
set
{
m_FieldD = value;
bSetFieldD = true;
}
}
public TableDemo()
{
SqlCmd = new System.Data.SqlClient.SqlCommand();
}
public TableDemo(int iID) : this()
{
m_ID = iID;
Load();
}
protected bool Load()
{
return Load(m_ID);
}
protected bool Load(int iID)
{
SqlCmd.Connection = GetSqlConnection();
SqlCmd.CommandText = "Select * From [" + _TableName + "] Where ([ID] = @ID)";
SqlCmd.Parameters.Add("@ID", System.Data.SqlDbType.Int);
SqlCmd.Parameters["@ID"].Value = iID;
System.Data.SqlClient.SqlDataReader drFields;
drFields = SqlCmd.ExecuteReader();
bool bLoadSuccess = false;
if ( drFields.Read() )
{
object objFieldA = drFields["FieldA"];
if ( !( objFieldA is System.DBNull ) )
{
m_FieldA = (System.String)drFields["FieldA"];
}
object objFieldB = drFields["FieldB"];
if ( !( objFieldB is System.DBNull ) )
{
m_FieldB = (System.String)drFields["FieldB"];
}
object objFieldC = drFields["FieldC"];
if ( !( objFieldC is System.DBNull ) )
{
m_FieldC = (System.DateTime)drFields["FieldC"];
}
object objFieldD = drFields["FieldD"];
if ( !( objFieldD is System.DBNull ) )
{
m_FieldD = (System.Decimal)drFields["FieldD"];
}
bLoadSuccess = true;
}
bool bNonUnique = drFields.Read();
drFields.Close();
drFields = null;
SqlCmd.Connection.Close();
SqlCmd.Parameters.Clear();
if ( bNonUnique || !bLoadSuccess )
{
string strMessage = "The identity isn't unique.";
throw new System.Exception(strMessage);
}
m_ID = iID;
return bLoadSuccess;
}
/**//// <summary>
/// Save datas
/// </summary>
public void Save()
{
Save(m_ID);
}
/**//// <summary>
/// Save the datas of row which ID equal iIdentity.
/// </summary>
/// <param name="iIdentity"></param>
private void Save(int iIdentity)
{
if ( iIdentity <= 0 )
{
SaveAs();
return;
}
System.Text.StringBuilder strbSql;
strbSql = new System.Text.StringBuilder();
strbSql.Append("Update [" + _TableName + "] Set");
System.Data.SqlClient.SqlParameterCollection spc;
spc = SqlCmd.Parameters;
if ( bSetFieldA )
{
strbSql.Append(", [FieldA] = @FieldA");
spc.Add("@FieldA", System.Data.SqlDbType.NVarChar, 50);
spc["@FieldA"].Value = m_FieldA;
bSetFieldA = false;
}
if ( bSetFieldB )
{
strbSql.Append(", [FieldB] = @FieldB");
spc.Add("@FieldB", System.Data.SqlDbType.NText);
spc["@FieldB"].Value = m_FieldB;
bSetFieldB = false;
}
if ( bSetFieldC )
{
strbSql.Append(", [FieldC] = @FieldC");
spc.Add("@FieldC", System.Data.SqlDbType.DateTime);
spc["@FieldC"].Value = m_FieldC;
bSetFieldC = false;
}
if ( bSetFieldD )
{
strbSql.Append(", [FieldD] = @FieldD");
spc.Add("@FieldD", System.Data.SqlDbType.Decimal);
spc["@FieldD"].Value = m_FieldD;
bSetFieldD = false;
}
if( spc.Count > 0 )
{
spc.Add("@ID", System.Data.SqlDbType.Int);
spc["@ID"].Value = m_ID;
strbSql.Append(" Where ([ID] = @ID)");
strbSql.Replace(" Set,", " Set ");
SqlCmd.CommandText = strbSql.ToString();
SqlCmd.Connection = GetSqlConnection();
SqlCmd.ExecuteNonQuery();
SqlCmd.Connection.Close();
SqlCmd.Parameters.Clear();
m_ID = iIdentity;
}
}
/**//// <summary>
/// Save the datas of current row to the new data row.
/// </summary>
public void SaveAs()
{
System.Data.SqlClient.SqlParameterCollection spc;
spc = SqlCmd.Parameters;
System.Text.StringBuilder strbValues;
strbValues = new System.Text.StringBuilder();
if ( bSetFieldA )
{
strbValues.Append(", @FieldA");
spc.Add("@FieldA", System.Data.SqlDbType.NVarChar, 50);
spc["@FieldA"].Value = m_FieldA;
bSetFieldA = false;
}
if ( bSetFieldB )
{
strbValues.Append(", @FieldB");
spc.Add("@FieldB", System.Data.SqlDbType.NText);
spc["@FieldB"].Value = m_FieldB;
bSetFieldB = false;
}
if ( bSetFieldC )
{
strbValues.Append(", @FieldC");
spc.Add("@FieldC", System.Data.SqlDbType.DateTime);
spc["@FieldC"].Value = m_FieldC;
bSetFieldC = false;
}
if ( bSetFieldD )
{
strbValues.Append(", @FieldD");
spc.Add("@FieldD", System.Data.SqlDbType.Decimal);
spc["@FieldD"].Value = m_FieldD;
bSetFieldD = false;
} string strFields, strValues;
if ( strbValues.Length > 3 )
{
SqlCmd.Connection = GetSqlConnection();
strValues = strbValues.ToString().Substring(2);
strFields = strbValues.Replace(", @", "], [").ToString();
strFields = strFields.Substring(3);
SqlCmd.CommandText = "Insert Into [" + _TableName + "] (" + strFields
+ "]) Values(" + strValues + ")";
lock(this)
{
SqlCmd.ExecuteNonQuery();
SqlCmd.CommandText = "Select @@IDENTITY";
m_ID = System.Convert.ToInt32(SqlCmd.ExecuteScalar());
}
SqlCmd.Connection.Close();
SqlCmd.Parameters.Clear();
}
}
/**//// <summary>
/// Copy the row to destination row which ID equal iDesID.
/// </summary>
/// <param name="iDesID"></param>
public void CopyTo(int iDesID)
{
bSetFieldA = true;
bSetFieldB = true;
bSetFieldC = true;
bSetFieldD = true;
Save(iDesID);
}
~TableDemo()
{
SqlCmd.Dispose();
}
/**//// <summary>
/// Create and return the database connection
/// </summary>
/// <returns>the opened database connection</returns>
protected static System.Data.SqlClient.SqlConnection GetSqlConnection()
{
string strConn = "SqlConnectionString";
strConn = System.Configuration.ConfigurationSettings.AppSettings[strConn];
System.Data.SqlClient.SqlConnection SqlConn;
SqlConn = new System.Data.SqlClient.SqlConnection(strConn);
SqlConn.Open();
return SqlConn;
}
private static int GetValue(string strSql)
{
System.Data.SqlClient.SqlCommand SqlCmd;
SqlCmd = new System.Data.SqlClient.SqlCommand();
SqlCmd.Connection = GetSqlConnection();
SqlCmd.CommandText = strSql;
object obj = SqlCmd.ExecuteScalar();
SqlCmd.Connection.Close();
if ( obj is System.DBNull ) return -1;
return (int)obj;
}
public static int GetMaxID()
{
string strSql = "Select Max(ID) From [{0}]";
return GetValue(String.Format(strSql, _TableName));
}
public static bool IsValueExist(string strUnique, string strValue, int iExceptID)
{
System.Data.SqlClient.SqlCommand SqlCmd;
SqlCmd = new System.Data.SqlClient.SqlCommand();
SqlCmd.Connection = GetSqlConnection();
string strSql = "Select Count(*) From [{0}] Where ([{1}] = @Value)";
strSql = String.Format(strSql, _TableName, strUnique);
SqlCmd.Parameters.Add("@Value", System.Data.SqlDbType.NVarChar).Value = strValue;
if ( iExceptID >= 0 )
{
strSql = String.Format("{0} AND ([ID] <> '{1}')", strSql, iExceptID);
}
SqlCmd.CommandText = strSql;
int iCount = (int)SqlCmd.ExecuteScalar();
SqlCmd.Connection.Close();
return !(iCount == 0);
}
public static bool IsValueExist(string strUnique, string strValue)
{
return IsValueExist(strUnique, strValue, -1);
}
}
#endregion
/// Automatically Code for Table 'TableDemo',
/// by Birdshome AutoCode Engine V.1.0
/// Copyright (C) 2004.1 Birdshome, HIT
/// </summary>
TableDemo Class#region TableDemo Class
public class TableDemo
{
private System.Int32 m_ID;
private System.String m_FieldA;
private System.String m_FieldB;
private System.DateTime m_FieldC;
private System.Decimal m_FieldD;
private System.Data.SqlClient.SqlCommand SqlCmd;
private bool bSetFieldA = false;
private bool bSetFieldB = false;
private bool bSetFieldC = false;
private bool bSetFieldD = false;
private static string _TableName = "TableDemo";
public System.Int32 ID
{
get
{
return m_ID;
}
}
public System.String FieldA
{
get
{
return m_FieldA;
}
set
{
if ( value != null && m_FieldA != value )
{
m_FieldA = value;
bSetFieldA = true;
}
}
}
public System.String FieldB
{
get
{
return m_FieldB;
}
set
{
if ( value != null && m_FieldB != value )
{
m_FieldB = value;
bSetFieldB = true;
}
}
}
public System.DateTime FieldC
{
get
{
return m_FieldC;
}
set
{
m_FieldC = value;
bSetFieldC = true;
}
}
public System.Decimal FieldD
{
get
{
return m_FieldD;
}
set
{
m_FieldD = value;
bSetFieldD = true;
}
}
public TableDemo()
{
SqlCmd = new System.Data.SqlClient.SqlCommand();
}
public TableDemo(int iID) : this()
{
m_ID = iID;
Load();
}
protected bool Load()
{
return Load(m_ID);
}
protected bool Load(int iID)
{
SqlCmd.Connection = GetSqlConnection();
SqlCmd.CommandText = "Select * From [" + _TableName + "] Where ([ID] = @ID)";
SqlCmd.Parameters.Add("@ID", System.Data.SqlDbType.Int);
SqlCmd.Parameters["@ID"].Value = iID;
System.Data.SqlClient.SqlDataReader drFields;
drFields = SqlCmd.ExecuteReader();
bool bLoadSuccess = false;
if ( drFields.Read() )
{
object objFieldA = drFields["FieldA"];
if ( !( objFieldA is System.DBNull ) )
{
m_FieldA = (System.String)drFields["FieldA"];
}
object objFieldB = drFields["FieldB"];
if ( !( objFieldB is System.DBNull ) )
{
m_FieldB = (System.String)drFields["FieldB"];
}
object objFieldC = drFields["FieldC"];
if ( !( objFieldC is System.DBNull ) )
{
m_FieldC = (System.DateTime)drFields["FieldC"];
}
object objFieldD = drFields["FieldD"];
if ( !( objFieldD is System.DBNull ) )
{
m_FieldD = (System.Decimal)drFields["FieldD"];
}
bLoadSuccess = true;
}
bool bNonUnique = drFields.Read();
drFields.Close();
drFields = null;
SqlCmd.Connection.Close();
SqlCmd.Parameters.Clear();
if ( bNonUnique || !bLoadSuccess )
{
string strMessage = "The identity isn't unique.";
throw new System.Exception(strMessage);
}
m_ID = iID;
return bLoadSuccess;
}
/**//// <summary>
/// Save datas
/// </summary>
public void Save()
{
Save(m_ID);
}
/**//// <summary>
/// Save the datas of row which ID equal iIdentity.
/// </summary>
/// <param name="iIdentity"></param>
private void Save(int iIdentity)
{
if ( iIdentity <= 0 )
{
SaveAs();
return;
}
System.Text.StringBuilder strbSql;
strbSql = new System.Text.StringBuilder();
strbSql.Append("Update [" + _TableName + "] Set");
System.Data.SqlClient.SqlParameterCollection spc;
spc = SqlCmd.Parameters;
if ( bSetFieldA )
{
strbSql.Append(", [FieldA] = @FieldA");
spc.Add("@FieldA", System.Data.SqlDbType.NVarChar, 50);
spc["@FieldA"].Value = m_FieldA;
bSetFieldA = false;
}
if ( bSetFieldB )
{
strbSql.Append(", [FieldB] = @FieldB");
spc.Add("@FieldB", System.Data.SqlDbType.NText);
spc["@FieldB"].Value = m_FieldB;
bSetFieldB = false;
}
if ( bSetFieldC )
{
strbSql.Append(", [FieldC] = @FieldC");
spc.Add("@FieldC", System.Data.SqlDbType.DateTime);
spc["@FieldC"].Value = m_FieldC;
bSetFieldC = false;
}
if ( bSetFieldD )
{
strbSql.Append(", [FieldD] = @FieldD");
spc.Add("@FieldD", System.Data.SqlDbType.Decimal);
spc["@FieldD"].Value = m_FieldD;
bSetFieldD = false;
}
if( spc.Count > 0 )
{
spc.Add("@ID", System.Data.SqlDbType.Int);
spc["@ID"].Value = m_ID;
strbSql.Append(" Where ([ID] = @ID)");
strbSql.Replace(" Set,", " Set ");
SqlCmd.CommandText = strbSql.ToString();
SqlCmd.Connection = GetSqlConnection();
SqlCmd.ExecuteNonQuery();
SqlCmd.Connection.Close();
SqlCmd.Parameters.Clear();
m_ID = iIdentity;
}
}
/**//// <summary>
/// Save the datas of current row to the new data row.
/// </summary>
public void SaveAs()
{
System.Data.SqlClient.SqlParameterCollection spc;
spc = SqlCmd.Parameters;
System.Text.StringBuilder strbValues;
strbValues = new System.Text.StringBuilder();
if ( bSetFieldA )
{
strbValues.Append(", @FieldA");
spc.Add("@FieldA", System.Data.SqlDbType.NVarChar, 50);
spc["@FieldA"].Value = m_FieldA;
bSetFieldA = false;
}
if ( bSetFieldB )
{
strbValues.Append(", @FieldB");
spc.Add("@FieldB", System.Data.SqlDbType.NText);
spc["@FieldB"].Value = m_FieldB;
bSetFieldB = false;
}
if ( bSetFieldC )
{
strbValues.Append(", @FieldC");
spc.Add("@FieldC", System.Data.SqlDbType.DateTime);
spc["@FieldC"].Value = m_FieldC;
bSetFieldC = false;
}
if ( bSetFieldD )
{
strbValues.Append(", @FieldD");
spc.Add("@FieldD", System.Data.SqlDbType.Decimal);
spc["@FieldD"].Value = m_FieldD;
bSetFieldD = false;
} string strFields, strValues;
if ( strbValues.Length > 3 )
{
SqlCmd.Connection = GetSqlConnection();
strValues = strbValues.ToString().Substring(2);
strFields = strbValues.Replace(", @", "], [").ToString();
strFields = strFields.Substring(3);
SqlCmd.CommandText = "Insert Into [" + _TableName + "] (" + strFields
+ "]) Values(" + strValues + ")";
lock(this)
{
SqlCmd.ExecuteNonQuery();
SqlCmd.CommandText = "Select @@IDENTITY";
m_ID = System.Convert.ToInt32(SqlCmd.ExecuteScalar());
}
SqlCmd.Connection.Close();
SqlCmd.Parameters.Clear();
}
}
/**//// <summary>
/// Copy the row to destination row which ID equal iDesID.
/// </summary>
/// <param name="iDesID"></param>
public void CopyTo(int iDesID)
{
bSetFieldA = true;
bSetFieldB = true;
bSetFieldC = true;
bSetFieldD = true;
Save(iDesID);
}
~TableDemo()
{
SqlCmd.Dispose();
}
/**//// <summary>
/// Create and return the database connection
/// </summary>
/// <returns>the opened database connection</returns>
protected static System.Data.SqlClient.SqlConnection GetSqlConnection()
{
string strConn = "SqlConnectionString";
strConn = System.Configuration.ConfigurationSettings.AppSettings[strConn];
System.Data.SqlClient.SqlConnection SqlConn;
SqlConn = new System.Data.SqlClient.SqlConnection(strConn);
SqlConn.Open();
return SqlConn;
}
private static int GetValue(string strSql)
{
System.Data.SqlClient.SqlCommand SqlCmd;
SqlCmd = new System.Data.SqlClient.SqlCommand();
SqlCmd.Connection = GetSqlConnection();
SqlCmd.CommandText = strSql;
object obj = SqlCmd.ExecuteScalar();
SqlCmd.Connection.Close();
if ( obj is System.DBNull ) return -1;
return (int)obj;
}
public static int GetMaxID()
{
string strSql = "Select Max(ID) From [{0}]";
return GetValue(String.Format(strSql, _TableName));
}
public static bool IsValueExist(string strUnique, string strValue, int iExceptID)
{
System.Data.SqlClient.SqlCommand SqlCmd;
SqlCmd = new System.Data.SqlClient.SqlCommand();
SqlCmd.Connection = GetSqlConnection();
string strSql = "Select Count(*) From [{0}] Where ([{1}] = @Value)";
strSql = String.Format(strSql, _TableName, strUnique);
SqlCmd.Parameters.Add("@Value", System.Data.SqlDbType.NVarChar).Value = strValue;
if ( iExceptID >= 0 )
{
strSql = String.Format("{0} AND ([ID] <> '{1}')", strSql, iExceptID);
}
SqlCmd.CommandText = strSql;
int iCount = (int)SqlCmd.ExecuteScalar();
SqlCmd.Connection.Close();
return !(iCount == 0);
}
public static bool IsValueExist(string strUnique, string strValue)
{
return IsValueExist(strUnique, strValue, -1);
}
}
#endregion
我比较懒,没有用View,直接就构建SQL操作表。
如果这种东西有用处,我就在好好收拾它一下,再release。
posted on 2004-08-27 13:53 birdshome 阅读(3024) 评论(7) 编辑 收藏 举报