你写数据库连接还这样写吗?
老土写法。。当要改一个用户名时。你就要从新改这个类。就要重新编译。在下下面有一个很好的方法
这个是原始的写法。
public class DBManager {
private static final String DRIVER = "com.mysql.jdbc.Driver";
//private static final String DRIVER = "com.microsoft.jdbc.sqlserver.SQLServerDriver";
private static final String URL = "jdbc:mysql://localhost:3306/test";
//private static final String URL = "jdbc:microsoft:sqlserver://localhost:1433;DatabaseName=test";
private static final String USERNAME = "root";
private static final String PASSWORD = "";
static {
try {
Class.forName(DRIVER);
} catch (ClassNotFoundException e) {
// TODO 自动生成 catch 块
e.printStackTrace();
}
}
public static Connection getConnection() {
Connection conn = null;
try {
conn = DriverManager.getConnection(URL, USERNAME, PASSWORD);
} catch (SQLException e) {
// TODO 自动生成 catch 块
e.printStackTrace();
}
return conn;
}
public static void closeAll(ResultSet rs, Statement state, Connection conn) {
try {
if (rs != null)
rs.close();
if (state != null)
state.close();
if (conn != null)
conn.close();
} catch (SQLException e) {
}
}
public static void main(String[] args) {
Connection conn = DBManager.getConnection();
}
}
学士版的写法动态的。。。最好用这种。
先建一个文件为属性文件。如config.properties
然后建一个读文件属性的类如下
新的写法。。。。。
public class ConnectionConfig {
private static ResourceBundle config = null;
static {
config = ResourceBundle.getBundle("emp.util.db.conndb");
}
public static String getUserName() {
return config.getString("USERNAME");
}
public static String getPassword() {
return config.getString("PASSWORD");
}
public static String getDriver() {
return config.getString("DRIVER");
}
public static String getUrl() {
return config.getString("URL");
}
}
再把上面的改一改。。。把你的数据据库配制的数据放在文件里。如下写
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.sql.SQLException;
public class DBManager {
static {
try {
Class.forName(ConnectionConfig.getDriver());
} catch (ClassNotFoundException e) {
// TODO 自动生成 catch 块
e.printStackTrace();
}
}
public static Connection getConnection() {
Connection conn = null;
try {
conn = DriverManager.getConnection(ConnectionConfig.getUrl(), ConnectionConfig.getUserName(), ConnectionConfig.getPassword());
} catch (SQLException e) {
// TODO 自动生成 catch 块
e.printStackTrace();
}
return conn;
}
public static void closeAll(ResultSet rs, Statement state, Connection conn) {
try {
if (rs != null)
rs.close();
if (state != null)
state.close();
if (conn != null)
conn.close();
} catch (SQLException e) {
}
}
}