java连接数据库以及连接参数格式

时间:2022-09-18 17:21:28

//链接数据库代码部分  下面具有连接的基本参数可以对照修改(参数存放在file下面的database.properties下面)

//参数存放在file下面的database.properties下面

driverClass=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/day36
username=root
password=root

//链接数据库代码部分

package cn.jy.demo;

import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;
public class JDBCUtilsConfig {
private static Connection con;
private static String driverClass;
private static String url;
private static String username;
private static String password;
static {
try {
readConfig();
Class.forName(driverClass);
con=DriverManager.getConnection(url,username,password);
} catch (Exception e) {
throw new RuntimeException("数据库连接失败");
}

}
private static void readConfig() throws IOException{
InputStream in=JDBCUtilsConfig.class.getClassLoader().getResourceAsStream("database.properties");
Properties pro = new Properties();
pro.load(in);
driverClass=pro.getProperty("driverClass");
url=pro.getProperty("url");
username=pro.getProperty("username");
password=pro.getProperty("password");
}
public static Connection getConnection(){
return con;
}
public static void close(Connection con, Statement stat){
if(stat!=null){
try {
stat.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if(con!=null){
try {
con.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
public static void close(Connection con, Statement stat,ResultSet rs){
if(rs!=null){
try {
rs.close();
} catch (SQLException e) {

e.printStackTrace();
}
if(stat!=null){
try {
stat.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if(con!=null){
try {
con.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
}