1...
/// 通用新增方法(批量)/// </summary>
/// <param name="arr">多行数据封装的集合</param>
/// <param name="tableName">表名</param>
/// <returns>结果 为true 成功</returns>
public bool Inserts(List<Dictionary<string, object>>arr, string tableName)
{
SqlConnection con = null;
SqlTransaction tr = null;
try
{
con = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["con"].ConnectionString);
con.Open();
tr = con.BeginTransaction();
foreach (Dictionary<string, object> ar in arr)
{
string sql = "insert into " + tableName + "(";
string sql2 = ")values(";
SqlCommand com = new SqlCommand(sql, con);
com.Transaction = tr;
foreach (KeyValuePair<string, object> ak in ar)
{
sql += ak.Key + ",";
sql2 += "@" + ak.Key + ",";
SqlParameter sp = new SqlParameter("@" + ak.Key, ak.Value.GetType());
sp.Value = ak.Value;
com.Parameters.Add(sp);
}
com.CommandText = sql.Substring(0, sql.Length - 1) + sql2.Substring(0, sql2.Length - 1) + ")";
com.ExecuteNonQuery();
}
tr.Commit();
return true;
}
catch (Exception ex)
{
tr.Rollback();
Console.Write(ex.Message);
return false;
}
finally
{
if (con.State == ConnectionState.Open) con.Close();
}
}
2.
/// <summary>
/// 通用新增方法(实体)
/// </summary>
/// <param name="bean">实体</param>
/// <param name="tableName">表名</param>
/// <returns></returns>
public bool Insert(object bean, string tableName)
{
SqlConnection con = null;
try
{
con = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["con"].ConnectionString);
con.Open();
Type t = bean.GetType();
System.Reflection.PropertyInfo[] pars = t.GetProperties();
string sql = "insert into " + tableName + "(";
string sql2 = ")values(";
SqlCommand com = new SqlCommand(sql, con);
foreach (System.Reflection.PropertyInfo p in pars)
{
sql += p.Name + ",";
sql2 += "@" + p.Name + ",";
SqlParameter sp = new SqlParameter("@" + p.Name, p.PropertyType);
sp.Value = p.GetValue(bean, null);
com.Parameters.Add(sp);
}
com.CommandText = sql.Substring(0, sql.Length - 1) + sql2.Substring(0, sql2.Length - 1) + ")";
return Convert.ToBoolean(com.ExecuteNonQuery());
}
catch (Exception ex)
{
Console.Write(ex.Message);
return false;
}
finally
{
if (con.State == ConnectionState.Open) con.Close();
}
}