java读取sql脚本文件并写入数据库

来源:互联网 发布:zeppelin软件下载 编辑:程序博客网 时间:2024/05/17 04:00

1.java读文件防止中文乱码:保证文件、数据库、表属性字段统一编码;之后创建连接时候指定编码useUnicode=true&characterEncoding=utf-8

2.BufferReader 逐行读取,批量插入数据库



package com.ally;import java.io.*;import java.sql.*;/** * 读取指定文件下sql脚本,执行到数据库 * 朱行读取分批处理批量插入数据库 */public class TestReadFile {    public static void main(String[] args) {        System.err.println("begin");        long start = System.currentTimeMillis();        String path = "D:\\drug_general_info.sql";        getData(path);        System.err.print((System.currentTimeMillis() - start) / 1000);    }    private static void getData(String path) {        //读取文件        BufferedReader reader;        Connection conn = null;        Statement pst = null;        try {            Class.forName("com.mysql.jdbc.Driver");            conn = DriverManager.getConnection(                    "jdbc:mysql://localhost:3306/doctor?useUnicode=true&characterEncoding=utf-8", "root", "root");            pst = conn.createStatement();            reader = new BufferedReader(new InputStreamReader(new FileInputStream(path), "UTF-8"));            String line;            int i = 0;            while ((line = reader.readLine()) != null) {                pst.addBatch(line);                  /*  System.out.println("-----------------------");                    System.out.println(line);                    System.out.println("-----------------------");*/                if (i % 100 == 0) {                    System.out.println("执行了:" + i);                     pst.executeBatch();                }                i += 1;            }            reader.close();            // 执行批量更新            pst.executeBatch();        } catch (Exception e) {            e.printStackTrace();        } finally {            try {                if (pst != null) {                    pst.close();                }                if (conn != null) {                    conn.close();                }            } catch (SQLException e) {                e.printStackTrace();            }        }    }}


0 0
原创粉丝点击