批量导入数据到数据库

//connectionString  连接数据库字符串    TableName 需要导入的数据表名  dt 需要导入的DataTable 

private bool SqlBulkCopyByDatatable(string connectionString, string TableName, System.Data.DataTable dt)
{
    using (System.Data.SqlClient.SqlConnection conn = new System.Data.SqlClient.SqlConnection(connectionString))
    {
      using (Sys  tem.Data.SqlClient.SqlBulkCopy sqlbulkcopy = new System.Data.SqlClient.SqlBulkCopy(connectionString, System.Data.SqlClient.SqlBulkCopyOptions.UseInternalTransaction))
        {
          try
          {
            sqlbulkcopy.DestinationTableName = TableName;
              for (int i = 0; i < dt.Columns.Count; i++)
                {
                  sqlbulkcopy.ColumnMappings.Add(dt.Columns[i].ColumnName, dt.Columns[i].ColumnName);
                }
                sqlbulkcopy.WriteToServer(dt);
                return true;
                }
                catch (System.Exception ex)
                {
                  throw ex;
                return false;
                }
              }
          }
      }

转载于:https://www.cnblogs.com/fengmingming/p/6068056.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
批量导入Excel到数据库,可以使用Java中的Apache POI和JDBC技术。以下是一个简单的示例代码: ```java import java.io.FileInputStream; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.Row; import org.apache.poi.ss.usermodel.Sheet; import org.apache.poi.xssf.usermodel.XSSFWorkbook; public class ExcelToDatabase { public static void main(String[] args) { String url = "jdbc:mysql://localhost:3306/mydatabase"; String username = "root"; String password = "password"; try (Connection conn = DriverManager.getConnection(url, username, password)) { String sql = "INSERT INTO mytable (column1, column2, column3) VALUES (?, ?, ?)"; PreparedStatement statement = conn.prepareStatement(sql); FileInputStream inputStream = new FileInputStream("data.xlsx"); XSSFWorkbook workbook = new XSSFWorkbook(inputStream); Sheet sheet = workbook.getSheetAt(0); for (Row row : sheet) { Cell cell1 = row.getCell(0); Cell cell2 = row.getCell(1); Cell cell3 = row.getCell(2); statement.setString(1, cell1.getStringCellValue()); statement.setInt(2, (int) cell2.getNumericCellValue()); statement.setDouble(3, cell3.getNumericCellValue()); statement.addBatch(); } statement.executeBatch(); System.out.println("Data imported successfully!"); } catch (Exception e) { e.printStackTrace(); } } } ``` 在这个示例中,我们首先建立了一个JDBC连接,然后使用Apache POI从Excel文件中读取数据。我们将每一行数据插入到数据库表中,使用PreparedStatement对象来执行SQL语句。最后,我们使用executeBatch()方法来批量执行插入操作。 请注意,这个示例假设Excel文件中的第一列是字符串,第二列是整数,第三列是双精度浮点数。您需要根据实际情况进行适当的更改。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值