/// <summary>
/// 自动生成SQL语句,insert或update
/// </summary>
/// <param name="DataPanel">控件容器,只运行Panel</param>
/// <param name="Action">操作类型:add添加保存生成insert;edit编辑保存生成update</param>
/// <param name="TableName">表名</param>
/// <param name="Where">条件,修改时起作用</param>
/// <returns>生成的SQL语句</returns>
public static string DataBulidSqlControls(Panel DataPanel, string Action, string TableName, string Where)
{
string returnSql = "";
string clunmsList = "";
string clunmsNameList = "";
string clunmsValuesList = "";
string objName = "";
string objType = "";
string objValue = "";
bool objBool = false;
string
mySql = "";
switch (Action)
{
case "add":
returnSql = "insert into " + TableName + " ($clunms_name_list$) values($clunms_values_list$)";
mySql = "select top 1 * from " + TableName + "";
break;
case "edit":
returnSql = "update " + TableName + " set $clunms_list$ " + Where + " ";
mySql = "select top 1 * from " + TableName + Where + " ";
break;
}
Class.SqlServer.DataSqlServer dataSqlServer = new Class.SqlServer.DataSqlServer();
DataSet dataSet = dataSqlServer.dataSet(
mySql);
foreach (Control obj in DataPanel.Controls)
{
switch (obj.GetType().ToString())
{
case "System.Web.UI.WebControls.TextBox":
objName = ((System.Web.UI.WebControls.TextBox)obj).ID;
objName = objName.Substring(7);
objValue = FilterTextBox(((System.Web.UI.WebControls.TextBox)obj).Text);
objBool = true;
break;
case "System.Web.UI.HtmlControls.HtmlInputHidden":
objName = ((System.Web.UI.HtmlControls.HtmlInputHidden)obj).ID;
objName = objName.Substring(6);
objValue = ((System.Web.UI.HtmlControls.HtmlInputHidden)obj).Value;
objBool = true;
break;
case "System.Web.UI.WebControls.CheckBox":
objName = ((System.Web.UI.WebControls.CheckBox)obj).ID;
objName = objName.Substring(8);
objValue = ((System.Web.UI.WebControls.CheckBox)obj).Checked.ToString().ToUpper();
objBool = true;
break;
}
if (objBool)
{
if (clunmsList != "")
clunmsList += ",";
if (clunmsNameList != "")
clunmsNameList += ",";
if (clunmsValuesList != "")
clunmsValuesList += ",";
objType = dataSet.Tables[0].Columns[objName].DataType.ToString();
switch (objType)
{
case "System.String":
case "System.DateTime":
objValue = "'" + objValue + "'";
break;
case "System.Decimal":
case "System.Double":
case "System.Int16":
case "System.Int32":
case "System.Int64":
if (objValue == null || objValue == "")
objValue = "null";
break;
case "System.Boolean":
if (objValue == "TRUE")
objValue = "1";
else
objValue = "0";
break;
}
clunmsList += objName + "=" + objValue;
clunmsNameList += objName;
clunmsValuesList += objValue;
objBool = false;
}
}
returnSql = returnSql.Replace("$clunms_list$", clunmsList);
returnSql = returnSql.Replace("$clunms_name_list$", clunmsNameList);
returnSql = returnSql.Replace("$clunms_values_list$", clunmsValuesList);
dataSet.Dispose();
return returnSql;
}