1、首先我在根目录下创建了一个driver.properties文件用来保存一些参数,方便后期修改
内容如下:student是我的数据库的名字。大家可以发现连接什么数据库不重要,里面的方法都是一样的,只是driver.properties文件内容不同。
可以去这篇文章中查看,可以发现除了导入的jar包不一样,和这个配置文件不一样以外,其他的都是一样的。http://blog.youkuaiyun.com/qq_36748278/article/details/76861334
DRIVER = com.mysql.jdbc.Driver
URL = jdbc:mysql://127.0.0.1:3306/student?characterEncoding=UTF-8
USER = root
PASSWORD = root
2、创建数据库连接的BaseDAO文件
获取driver.properties文件中的各种属性的代码如下:
FileInputStream fis = null;
Properties properties = null;
try {
fis = new FileInputStream("driver.properties");
properties = new Properties();
properties.load(fis);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
String driver = properties.getProperty("DRIVER");
String url = properties.getProperty("URL");
String user = properties.getProperty("USER");
String password = properties.getProperty("PASSWORD");
连接Mysql和java程序的主要代码如下:
Connection con = null;
try {
Class.forName(driver);
con = DriverManager.getConnection(url, user, password);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
整个BaseDAO文件代码如下:
public class BaseDAO {
public Connection getConnection(){
//1、得到配置文件中的属性
FileInputStream fis = null;
Properties properties = null;
try {
fis = new FileInputStream("driver.properties");
properties = new Properties();
properties.load(fis);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
String driver = properties.getProperty("DRIVER");
String url = properties.getProperty("URL");
String user = properties.getProperty("USER");
String password = properties.getProperty("PASSWORD");
Connection con = null;
try {
Class.forName(driver);
con = DriverManager.getConnection(url, user, password);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
return con;
}
//关闭连接的方法
public void close(Connection con,Statement st,ResultSet rs){
try {
if(con != null){
con.close();
}
if(st != null){
st.close();
}
if(rs != null){
rs.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
//进行连接的测试
public static void main(String[] args) {
Connection con = new BaseDAO().getConnection();
try {
System.out.println(con.isClosed()); //false,说明连接没有关闭,成功了
} catch (SQLException e) {
e.printStackTrace();
}
}
}
把这个BaseDAO放在你的项目中,需要的时候直接调用这个类中的方法即可。