用配置文件连接数据库
1. Eclipse中,在src目录下建立db.properties文件,在里面配置数据库连接所需的 Driver,url,user,possword ,注意等号左右不能空格
如:
driver=com.microsoft.sqlserver.jdbc.SQLServerDriver
url=jdbc:sqlserver://localhost:1433;databaseName=restrant
user=sa
password=110
2.写一个数据库连接类
import java.io.IOException;
import java.sql.*;
import java.util.Properties;
public Connection getCon() {
Connection con = null;
Properties properties = new Properties();
try {
properties.load(this.getClass().getResourceAsStream(
"/db.properties"));
String driver = properties.getProperty("driver");
String url = properties.getProperty("url");
String user = properties.getProperty("user");
String password = properties.getProperty("password");
try {
Class.forName(driver);
con = DriverManager.getConnection(url, user, password);
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return con;
}