1.jdbc连接数据库
public class mysqlConnector {
private Connection conn;
private String driver="com.mysql.jdbc.Driver";
private String url="jdbc:mysql://localhost:3306/test";
private String username="root";
private String password="123456";
public Connection getConnection(){
try {
//加载驱动
Class.forName(driver);
conn=DriverManager.getConnection(url, username, password);
if(conn!=null){
System.out.println("** mysql连接成功 **");
}
else{
System.out.println("** mysql连接失败 **");
}
} catch (Exception e) {
e.printStackTrace();
}
return conn;
}
}
2.使用properties配置文件连接mysql数据库
1)创建db.properties配置文件
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/userdatabase
username=root
password=123456
2)创建jdbcutil工具类,读取properties配置文件信息,连接mysql数据库
public class jdbcUtil {
public Connection conn;
private String driver;
private String url;
private String user;
private String password;
/**
* 连接mysql数据库
* @return
*/
public Connection getconnection() {
// 读取db.properties配置文件
InputStream input = this.getClass().getResourceAsStream("/db.properties");
Properties ps = new Properties();
try {
// 加载db.properties配置文件
ps.load(input);
driver = ps.getProperty("driver");
url = ps.getProperty("url");
user = ps.getProperty("username");
password = ps.getProperty("password");
// 加载驱动
Class.forName(driver);
conn = DriverManager.getConnection(url, user, password);
if (conn != null) {
System.out.println("mysql连接成功...");
} else {
System.out.println("mysql连接失败...");
}
} catch (Exception e) {
e.printStackTrace();
}
return conn;
}
/**
* 关闭mysql数据库连接
* @param conn
* @param pstmt
* @param rs
*/
public static void close(Connection conn, PreparedStatement pstmt,ResultSet rs) {
try {
if (conn != null) {
conn.close();
}
if (pstmt != null) {
pstmt.close();
}
if (rs != null) {
rs.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}