日期:2014-05-17 浏览次数:20462 次
/* 向数据库的各个表,插入数据 Insert */
protected void DBInsertData(DataTable dt, string dbName, string tableName, string[] columnName)
{
/* 声明、初始化变量 */
string allColName = ""; //所有的列名
for (int i = 0; i < columnName.Length; i++)
{
allColName += columnName[i] + ",";
}
allColName = allColName.Substring(0, allColName.Length - 1);
string allParaName = "@"; //所有的参数名
allParaName += allColName.Replace(",", ",@");
for (int i = 0; i < dt.Rows.Count; i++) //循环 是因为插入多行数据
{
string connstring = @"Data Source=.\SQLExpress;Initial Catalog=" + dbName + ";Integrated Security=True";//数据源;初始化;继承方式:安全模式SSPL
SqlConnection conn = new SqlConnection(connstring);
string insertstring = "insert into " + tableName + "(" + allColName + ") values (" + allParaName + ")";
SqlCommand scd = new SqlCommand(insertstring, conn);
for (int j = 0; j < columnName.Length; j++) //循环 向数据库插入数据
{
scd.Parameters.AddWithValue(columnName[j],dt.Rows[i][j].ToString()); //先后无所谓
//正确的形式是这样子的: scd.Parameters.AddWithValue("titleID", titleid);
}