mysql 实现批量导入,并解决中文乱码问题
public static String url = "jdbc:mysql://ip/database?characterEncoding=UTF-8"; //在database 后面加上?characterEncoding=UTF-8 就可以解决java 插入数据中文乱码问题 public static String username = "user"; public static String password = "123"; public static Connection conn; public static Statement stmt; public static ResultSet rs; public static DataStructure ds = new DataStructure(); /*public Connection getConnection() { try { Class.forName("com.mysql.jdbc.Driver"); } catch (ClassNotFoundException e1) { e1.printStackTrace(); } try { conn = DriverManager .getConnection("jdbc:mysql://ip/databases?user=user&password=pass&useUnicode=true&characterEncoding=utf-8"); conn = DriverManager.getConnection(url, username, password); } catch (Exception e) { e.printStackTrace(); } return conn; }*/ public void closeConnection(Connection conn) { if (conn != null) { try { conn.close(); } catch (SQLException e) { e.printStackTrace(); } } } /* // 实现查询操作 public static void select(String sql) { try { rs = stmt.executeQuery(sql); ResultSetMetaData meta_data = rs.getMetaData();// 列名 for (int i_col = 1; i_col <= meta_data.getColumnCount(); i_col++) { System.out.print(meta_data.getColumnLabel(i_col) + " "); } System.out.println(); while (rs.next()) { for (int i_col = 1; i_col <= meta_data.getColumnCount(); i_col++) { System.out.print(rs.getString(i_col) + " "); } System.out.println(); } rs.close(); } catch (Exception e) { System.out.println("数据查询失败!"); } }*/ public static void insertd(String sql) { try { conn = DriverManager.getConnection(url, username, password); conn.setAutoCommit(false); stmt = conn.prepareStatement("load data local infile '' " + "into table loadtest fields terminated by ','"); StringBuilder sb = new StringBuilder(); InputStream is = new ByteArrayInputStream(sb.toString().getBytes()); ((com.mysql.jdbc.Statement) stmt).setLocalInfileInputStream(is); stmt.executeUpdate(sql); conn.commit(); } catch (SQLException e) { e.printStackTrace(); } } public static void main(String[] args) { String sql = ("insert into bns_user (userurl, titleurl, createtime, username, titleabout ) values ('12','1','1','1','1')"); insertd(sql); }