jdbc.properties:
mysql.url=jdbc:mysql://192.168.12.120:3306/es_history?useUnicode=true&characterEncoding=utf8
mysql.username=root
mysql.password=12345678
mysql.driver=com.mysql.jdbc.Driver
========================================================
public class JdbcUtil {
private static Connection conn = null;private static Properties pro = new Properties();
//加载驱动,使用静态块,只需要加载一次
static {
try {
/**
* 加载配置文件的两种方法,任选一种都可以
*/
//pro.load(DBUtil.class.getResourceAsStream("/jdbc.properties"));
pro.load(JdbcUtil.class.getClassLoader().getResourceAsStream("jdbc.properties"));
String DRIVER = pro.getProperty("mysql.driver");
Class.forName(DRIVER);
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
//获取Connection连接对象的方法,使用static方便之后在其他类中调用
public static Connection getConn() {
try {
conn = DriverManager.getConnection(
pro.getProperty("mysql.url"),
pro.getProperty("mysql.username"),
pro.getProperty("mysql.password"));
} catch (SQLException e) {
e.printStackTrace();
}
return conn;
}
//关闭资源的方法
public static void close(ResultSet rs,PreparedStatement ps,Connection conn) {
if(rs!=null) {
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(ps!=null) {
try {
ps.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(conn!=null) {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
Connection conn2 = JdbcUtil.getConn();
try {
Statement cs = conn2.createStatement();//("select * from h_user");
ResultSet rs = cs.executeQuery("select * from h_user");
while(rs.next()){
System.out.println(rs.getInt(1));
System.out.println(rs.getString(2));
}
// //批量添加
// String sql = "insert into hot_user(name, count,create_time) values (?, ?,now())";
// conn2.setAutoCommit(false);//关闭自动提交
// PreparedStatement ps = conn.prepareStatement(sql);
// int num = 0;
// for (int i = 1; i <= 5000000; i++) {
// ps.setString(1, "user" + i);
// ps.setString(2, "pass" + i);
// ps.addBatch(); // 加入批量处理
// num ++;
// }
// ps.executeBatch(); // 执行批量处理
// conn.commit(); // 提交
// JdbcUtil.close(null, ps, conn2);//释放资源
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}