本文实例讲述了Java实现批量向mysql写入数据的方法。分享给大家供大家参考,具体如下:
private static String user = "root";private static String pass = "123456";private static String URL = "jdbc:mysql://192.168.1.116:3306/test";public static void main(String args[]) throws SQLException, ClassNotFoundException{ //获取时间信息 SimpleDateFormat sfmt = new SimpleDateFormat("yyyyMMddHHmmss"); Date lastHour = new Date(new Date().getTime() - 3600000);//1小时前 String hourMeta = sfmt.format(lastHour).substring(0, 10);//小时的时间戳,用于大数据缩小搜索范围 int day = Integer.parseInt(sfmt.format(lastHour).substring(0, 8)); int hour = Integer.parseInt(String.valueOf(lastHour.getHours())); //连接mysql数据库 Connection conn = DriverManager.getConnection(URL , user, pass); conn.setAutoCommit(false); //向mysql中插入数据 String sql = "insert into test1 values(?,?)"; PreparedStatement ps = conn.prepareStatement(sql);//要执行sql语句的对象 ps.setInt(1, day); ps.setInt(2, hour); //ps.setString(1, "aa"); //ps.setString(2, "bb"); ps.addBatch();//再添加一次预定义参数 ps.executeBatch();//执行批量执行 conn.commit(); if (ps != null) { ps.close(); } if (conn != null) { conn.close(); }}
希望本文所述对大家java程序设计有所帮助。
新闻热点
疑难解答
图片精选