省去数据库插入、修改繁琐操作。
/// <summary>
/// post表单提交,表单数据存入数据库
/// post传入的参数(表单name值),必须与数据库中列名一样
/// </summary>
/// <param name="tableName">数据库表名</param>
/// <param name="primaryKey">表中主键字段</param>
/// <param name="primaryKeyValue">主键字段的值,如果为空表示插入操作,否则编辑操作</param>
public void SaveTableInsertOrUpdateFormPostParameters(string tableName, string primaryKey, string primaryKeyValue)
{
string sqlColumn = "";
string sqlValue = "";
string sql = "";
//参数数组
System.Data.SqlClient.SqlParameter[] parameters = new System.Data.SqlClient.SqlParameter[Request.Form.Keys.Count];
//插入操作
if (string.IsNullOrEmpty(primaryKeyValue))
{
for (int i = 0; i < Request.Form.Keys.Count; i++)//循环获取post形式的参数及参数值
{
string column = Request.Form.Keys[i];//数据库列名
string value = Request.Form[i];//获取表单的值
sqlColumn += column + ",";
string parmColumn = "@" + column;
sqlValue += parmColumn + ",";
if (string.IsNullOrEmpty(value))
{
parameters[i] = new System.Data.SqlClient.SqlParameter(parmColumn, DBNull.Value);
}
else
{
//如果存在汉字编码问题,前台javascript使用escape编码,后台使用Server.UrlDecode()解码
parameters[i] = new System.Data.SqlClient.SqlParameter(parmColumn, Server.UrlDecode(value));
}
}
sqlColumn = sqlColumn.Substring(0, sqlColumn.Length - 1);
sqlValue = sqlValue.Substring(0, sqlValue.Length - 1);
sql = " insert into " + tableName + " (" + sqlColumn + ") values (" + sqlValue + ")";
}
else//修改操作
{
for (int i = 0; i < Request.Form.Keys.Count; i++)
{
string column = Request.Form.Keys[i];
string parmColumn = "@" + column;
sql += column + "=" + parmColumn + ",";
string value = Request.Form[i];
if (string.IsNullOrEmpty(value))
{
parameters[i] = new System.Data.SqlClient.SqlParameter(parmColumn, DBNull.Value);
}
else
{
value = Server.UrlDecode(value);
parameters[i] = new System.Data.SqlClient.SqlParameter(parmColumn, value);
}
}
//string where = " where " + primaryKey + "=@" + primaryKey;
//SqlParameter 数组大小需要修改把主键加入到参数数组中
sql = sql.Substring(0, sql.Length - 1);
sql = " update " + tableName + " set " + sql + " where " + primaryKey + "='" + primaryKeyValue + "'";
}
//数据库访问类,根据实际条件修改
DbHelperSQLNew db = new DbHelperSQLNew();
Response.Write(db.ExecuteSql(sql, parameters).ToString());//ExecuteSql执行一条sql语句
}