1:创建步骤
a:导入Maven工程——resources——new File——db.properties
b:将下面四条代码放入db.properties
diver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/test //test是我自己的数据库表名
user=root
password=root //输入自己的密码
c:在src下建立正常包或者类
2:代码实现
补充:try...catch...语句快捷键“Ctrl+Alt+t”,在你想要被try...catch...语句包语句上操作围的
package com.pp;
import java.sql.*;
import java.util.ResourceBundle;
public class JdbcUtil {
private static String diver;
private static String url;
private static String user;
private static String password;
static {
try {
ResourceBundle bundle = ResourceBundle.getBundle("db");
diver=bundle.getString("diver");
url=bundle.getString("url");
user=bundle.getString("user");
password=bundle.getString("password");
} catch (Exception e) {
e.printStackTrace();
}
}
public static Connection getConnection(){
try {
Class.forName(diver);
Connection connection = DriverManager.getConnection(url, user, password);
return connection;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public static void closeResouce(Connection connection,Statement statement,ResultSet resultSet){
CloseResultSet(resultSet);
Closestatement(statement);
CloseConnection(connection);
}
public static void CloseConnection(Connection connection){
if (connection!=null){
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
connection=null;
}
}
public static void Closestatement(Statement statement){
if (statement!=null){
try {
statement.close();
} catch (SQLException e) {
e.printStackTrace();
}
statement=null;
}
}
public static void CloseResultSet(ResultSet resultSet){
if (resultSet!=null){
try {
resultSet.close();
} catch (SQLException e) {
e.printStackTrace();
}
resultSet=null;
}
}
}
网友评论