创建一个properties文件
1)mysql.driver=com.mysql.jdbc.Driver
mysql.url=jdbc:mysql://localhost:3306/flowerdb?characterEncoding=utf-8
mysql.user=root
mysql.pwd=123456
–>localhost:3306可省略不写,?后面设置接收的编码格式
2)mysql.driver=com.mysql.jdbc.Driver
mysql.url=jdbc:mysql:///flowerdb?characterEncoding=GBK
mysql.user=root
mysql.pwd=123456
DButil的类
–>注意导包
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.Properties;
private static String driverManage;
private static String url;
private static String user;
private static String pwd;
private static Properties ps=new Properties();
//静态代码块
static{
try {
InputStream is=DButil.class.getClassLoader().getResourceAsStream("org/dht/util/db.properties");
ps.load(is);
driverManage=ps.getProperty("mysql.driver");
url=ps.getProperty("mysql.url");
user=ps.getProperty("mysql.user");
pwd=ps.getProperty("mysql.pwd");
Class.forName(driverManage);
} catch (Exception e) {
// TODO: handle exception
}
}
//得到连接的工具方法
public static Connection getConn(){
Connection conn=null;
try {
conn=DriverManager.getConnection(url, user, pwd);
} catch (Exception e) {
// TODO: handle exception
}
return conn;
}
//关闭连接的工具类
public static void claseConn(Connection conn,PreparedStatement ps,ResultSet rs){
try {
if(conn!=null){
conn.close();
}
if(ps!=null){
ps.close();
}
if(rs!=null){
ps.close();
}
} catch (Exception e) {
// TODO: handle exception
}
}
public static void main(String[] args) {
System.out.println(getConn());
}