JDBC连接Mysql8
程序员文章站
2022-05-30 13:22:20
...
原生方式
public static void main(String[] args) throws Exception{
jdbc();
}
public static void jdbc() throws Exception {
final String DRIVER = "com.mysql.cj.jdbc.Driver";
final String URL = "jdbc:mysql://localhost:3306/myjdbctest?serverTimezone=CST";
final String USER = "root";
final String PASS = "w1234";
String sql = "select username,password from user";
Connection connection = null;
PreparedStatement preparedStatement = null;
ResultSet result=null;
try {
Class.forName(DRIVER);
connection = DriverManager.getConnection(URL, USER, PASS);
preparedStatement = connection.prepareStatement(sql);
result = preparedStatement.executeQuery();
while (result.next()) {
String str1 = result.getString(1);
String str2 = result.getString(2);
System.out.println(str1 + " --- " + str2);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (result!=null){
result.close();
}
if (preparedStatement != null) {
preparedStatement.close();
}
if (connection != null) {
connection.close();
}
}
}
连接池druid
配置文件
druid.properties
driverClassName=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://localhost:3306/myjdbctest?serverTimezone=CST
username=root
password=w1234
# 初始化大小
initialSize=5
# 最小空闲数
minIdle=10
# 最大活跃数
maxActive=20
# 获取连接的等待时间
maxWait=10000
# 间隔多长时间 检测是否关闭空闲连接 单位是毫秒
timeBetweenEvictionRunsMillis=2000
# 控制一个连接在资源池中 最大或最小的生存时间 单位也是毫秒
minEvictableIdleTimeMillis=600000
maxEvictableIdleTimeMillis=900000
public static void main(String[] args) throws Exception{
druid();
}
public static void druid() throws Exception {
String sql = "select username,password from user";
ResultSet result=null;
DataSource dataSource = null;
Connection connection = null;
PreparedStatement preparedStatement = null;
Properties properties = new Properties();
InputStream resourceAsStream = MainClass.class.getClassLoader().getResourceAsStream("druid.properties");
try {
properties.load(resourceAsStream);
dataSource = DruidDataSourceFactory.createDataSource(properties);
connection = dataSource.getConnection();
preparedStatement = connection.prepareStatement(sql);
result = preparedStatement.executeQuery();
while (result.next()) {
String str1 = result.getString(1);
String str2 = result.getString(2);
System.out.println(str1 + " --- " + str2);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (result!=null){
result.close();
}
if (preparedStatement != null) {
preparedStatement.close();
}
if (connection != null) {
connection.close();
}
if (resourceAsStream != null) {
resourceAsStream.close();
}
}
}
上一篇: XML之DTD