package cn.tedu.dao;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;
import org.apache.commons.dbcp2.BasicDataSource;
public class DBUtil {
private static BasicDataSource ds;
static {
try {
Properties cfg = new Properties();
InputStream in = DBUtil.class.getClassLoader().getResourceAsStream("jdbc.properties");
cfg.load(in);
ds = new BasicDataSource();
ds.setDriverClassName(cfg.getProperty("driver"));
ds.setUrl(cfg.getProperty("url"));
ds.setUsername(cfg.getProperty("username"));
ds.setPassword(cfg.getProperty("password"));
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException(e);
}
}
public static Connection getConnection() {
try {
return ds.getConnection();
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException(e);
}
}
public static void colse(Connection conn) {
try {
if(conn!=null) {
conn.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
@Test
public void testJDBC() throws Exception {
Class.forName("com.mysql.cj.jdbc.Driver");
String url = "jdbc:mysql://localhost:3306/db1?useUnicode=true&"
+ "characterEncoding=UTF-8&serverTimezone=Asia/Shanghai";
String username = "root";
String password = "root";
Connection conn = DriverManager.getConnection(url, username, password);
String sql = "select * from emp";
Statement st = conn.createStatement();
ResultSet rs = st.executeQuery(sql);
while(rs.next()) {
System.out.print(rs.getInt("empno")+"---");
System.out.println(rs.getString("ename"));
}
conn.close();
}