• datatable插入数据库


    使用sqlcommand.executenonquery()方法插入

    foreach (DataRow datarow in datatable.Rows)
    {
    string sql = "INSERT INTO [Table_1]

    ([CompanyName],[CompanyCode],[Address],[Owner],[Memo])" +
    "VALUES('" + datarow["CompanyName"].ToString() + "'" +
    ",'" + datarow["CompanyCode"].ToString() + "'" +
    ",'" + datarow["Address"].ToString() + "'" +
    ",'" + datarow["Owner"].ToString() + "'" +
    ",'" + datarow["Memo"].ToString() + "')";
    using (SqlConnection sqlconn = new SqlConnection(connectionString))
    {
          sqlconn.Open();

          SqlCommand sqlcommand = new SqlCommand(sql, sqlconn);
          sqlcommand.ExecuteNonQuery();
          sqlconn.Close();
    }
    }

    使用sqldataadapter.update(dataset,tablename);

    SqlCommand insertcommand = new SqlCommand("INSERT INTO [Table_1]([CompanyName],[CompanyCode],[Address],[Owner],[Memo])" +
    "VALUES(@CompanyName, @CompanyCode,@Address,@Owner,@Memo)",new SqlConnection(connectionString));
    insertcommand.Parameters.Add("@CompanyName", SqlDbType.NChar, 50, "CompanyName");
    insertcommand.Parameters.Add("@CompanyCode", SqlDbType.NChar, 25, "CompanyCode");
    insertcommand.Parameters.Add("@Address", SqlDbType.NChar, 255, "Address");
    insertcommand.Parameters.Add("@Owner", SqlDbType.NChar, 25, "Owner");
    insertcommand.Parameters.Add("@Memo", SqlDbType.NChar, 255, "Memo");
    sqldataadapter.InsertCommand = insertcommand;

    sqldataadapter.Update(dataset, "Table_1");

    使用sqlbulkcopy.writetoserver(datatable)

    SqlBulkCopy sqlbulkcopy = new SqlBulkCopy(connectionString, SqlBulkCopyOptions.UseInternalTransaction);
    sqlbulkcopy.DestinationTableName = "Table_1";//数据库中的表名

    sqlbulkcopy.WriteToServer(dataset.Tables[0]);

  • 相关阅读:
    学习笔记:字符串-Hash
    模板:高精度
    关于我自己
    学习笔记:数学-GCD与LCM-素数筛法
    学习笔记:数学-GCD与LCM-唯一分解定理(质因数分解)
    学习笔记:数学-GCD与LCM-整除的基础概念
    题解 洛谷P1990 覆盖墙壁
    学习笔记:平衡树-splay
    npm发布myself的插件
    javascript API文档
  • 原文地址:https://www.cnblogs.com/bloodofhero/p/1739108.html
Copyright © 2020-2023  润新知