Java链接MySQL数据库的用配置文件和不用配置文件的代码
1、利用配置文件(db.properties)链接MySQL数据库
package tool;
import java.io.FileInputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.util.Properties;
public class DBSource {
public static Connection getConn() {
Connection conn = null;
try {
Properties ps = new Properties();
ps.load(new FileInputStream("db.properties"));
String driver = ps.getProperty("driver");
String url = ps.getProperty("url");
String username = ps.getProperty("username");
String password = ps.getProperty("password");
Class.forName(driver);
conn = DriverManager.getConnection(url, username, password);
} catch (Exception e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
}
return conn;
}
public static void closeAll(Connection conn) {
try {
if (conn != null&&conn.isClosed())
conn.close();
} catch (Exception e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
}
}
}
2、没有利用配置文件(db.properties)链接MySQL数据库
package com.util;
import java.io.FileInputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;
public class DBSource {
public Connection getConn() {
Connection conn = null;
try {
Class.forName("com.mysql.jdbc.Driver");
String url = "jdbc:mysql://localhost:3306/renshoua?useUnicode=true&characterEncoding=utf8";
String username = "root";
String password = "root";
conn = DriverManager.getConnection(url, username, password);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return conn;
}
public void closeConn(Connection conn) {
try {
if (conn != null && !conn.isClosed()) {
conn.close();
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
注:请大家参考使用,如果有错请指出.谢谢!