采用JDBC去连接
JDBCUtils.java
public class JDBCUtils {
/**
* 使用Druid数据库连接池技术
*/
private static DataSource source;
static {
try {
Properties pros = new Properties();
InputStream is = ClassLoader.getSystemClassLoader().getResourceAsStream("druid.properties");
pros.load(is);
source = DruidDataSourceFactory.createDataSource(pros);
} catch (Exception e) {
e.printStackTrace();
}
}
public static Connection getConnection() throws SQLException {
Connection conn = source.getConnection();
return conn;
}
/**
* 使用dbutils.jar中提供的DbUtils工具类,实现资源的关闭
*/
public static void closeResource(Connection conn, Statement ps, ResultSet rs) {
DbUtils.closeQuietly(conn);
DbUtils.closeQuietly(ps);
DbUtils.closeQuietly(rs);
}
}
配置文件:
druid.properties
url=jdbc:mysql://localhost:3306/task
username=root
password=root
driverClassName=com.mysql.jdbc.Driver
需要的jar包:
测试连接:
public class Test {
static Connection conn = null;
public static void main(String[] args) throws SQLException {
conn = JDBCUtils.getConnection();
System.out.println(conn);
}
}
运行结果:
十月 23, 2020 11:53:54 上午 com.alibaba.druid.pool.DruidDataSource info
信息: {dataSource-1} inited
com.mysql.jdbc.JDBC4Connection@53e25b76
连接成功