是不是每次在写jdbc的时候,链接参数跟驱动加载什么的写的很头痛,来封装自己的jdbc吧!
思路:
1、将链接参数使用properties文件保存!!!注意哟
2、使用properties类读取链接参数,这样以后修改链接的数据库,不用修改源码文件
3、使用静态代码块读取参数,提高效率
4、封装获取connection对象的方法
5、封装statement对象的方法
6、preparedStatement方法
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;
public class TestJdbc {
private static String driver="";
private static String url="";
private static String user="";
private static String pwd="";
static{
Properties pt=new Properties();
try {
pt.load(SxtJdbc.class.getClassLoader().getResourceAsStream("myjdbc.properties"));
driver=pt.getProperty("driver");
url=pt.getProperty("url");
user=pt.getProperty("user");
pwd=pt.getProperty("pwd");
System.out.println(driver+"-"+url+"-"+user+"-"+pwd);
Class.forName(driver);
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
public static Connection getConnection(){
Connection conn=null;
try {
conn=DriverManager.getConnection(url, user, pwd);
} catch (SQLException e) {
System.err.println("链接参数异常:"+"["+url+"],"+"["+user+"],"+"["+pwd+"]");
e.printStackTrace();
}
return conn;
}
public static Statement getStatemenct(Connection conn){
Statement stmt=null;
try {
stmt=conn.createStatement();
} catch (SQLException e) {
e.printStackTrace();
}
return stmt;
}
public static PreparedStatement getPreparedStatment(Connection conn,String sql){
PreparedStatement ps=null;
try {
ps= conn.prepareStatement(sql);
} catch (SQLException e) {
e.printStackTrace();
}
return ps;
}
}
myjdbc.properties文件中参数列表
driver=oracle.jdbc.OracleDriver
url=jdbc:oracle:thin:@localhost:1521:orcl
user=test
pwd=1234