淺析一個簡單的JDBC例子
JDBC例子1,首先在配置文件(system.properties)中配置上如下內(nèi)容:
- driver=com.microsoft.sqlserver.jdbc.SQLServerDriver
- url=jdbc:sqlserver://localhost:1433;databaseName=mp
- username=sa
- password=mengya
JDBC例子2,寫了個SQLDB的工具類
- publicclassSQLDBConnection{
- privateInputStreaminputstr;
- privatePropertiespro;
- privatestaticSQLDBConnectionsqldb=null;
- //私有構(gòu)造方法
privateSQLDBConnection(){
inputstr=this.getClass().getResourceAsStream("/system.properties");
pro=newProperties();
try{
pro.load(inputstr);
}catch(IOExceptione){
e.printStackTrace();
}
try{
Class.forName(pro.getProperty("driver"));//注冊驅(qū)動,只注冊一次
}catch(ClassNotFoundExceptione){
e.printStackTrace();
}
}
//單例模式
publicstaticSQLDBConnectiongetSQLDBConnection(){
if(sqldb==null){
synchronized(SQLDBConnection.class){
if(sqldb==null){
sqldb=newSQLDBConnection();
}
}
}
returnsqldb;
}
//得到與數(shù)據(jù)庫的連接
publicConnectionGetConnection(){
Connectionconn=null;
try{
conn=DriverManager.getConnection(pro.getProperty("url"),pro.getProperty("username"),pro.getProperty("password"));
}catch(SQLExceptione){
e.printStackTrace();
}
returnconn;
}
JDBC例子3,寫好Studao的接口
- //釋放資源
- publicstaticvoidfree(ResultSetrs,Statementsta,Connectionconn){
- try{
- if(rs!=null){
- rs.close();
- }
- }catch(Exceptione){
- e.printStackTrace();
- }finally{
- try{
- if(sta!=null){
- sta.close();
- }
- }catch(Exceptione){
- e.printStackTrace();
- }finally{
- if(conn!=null){
- try{
- conn.close();
- }catch(SQLExceptione){
- e.printStackTrace();
- }
- }
- }
- }
- }
- publicinterfaceStudaointer{
- publicvoidaddStu(Stustu);
- publicvoiddelStu(intsid);
- publicvoidupdStu(Stustu);
- publicStugetOneStu(intsid);
- publicListgetAllStu();
- }
JDBC例子4,寫好自己定義的RuntimeException
- publicclassMySQLExceptionextendsRuntimeException{
- privatestaticfinallongserialVersionUID=1L;
- }
JDBC例子5,寫好Studao的實現(xiàn)類
- publicclassStuDAOImpleimplementsStudaointer{
- privateConnectionconn;
- privatePreparedStatementpre;
- privateResultSetrs;
- publicvoidaddStu(Stustu){
- Stringsql="insertintostuvalues(?,?,?)";
- conn=SQLDBConnection.getSQLDBConnection().GetConnection();
- try{
- pre=conn.prepareStatement(sql);
- pre.setString(1,stu.getSname());
- pre.setString(2,stu.getSsex());
- pre.setDate(3,newjava.sql.Date(stu.getSbrith().getTime()));
- pre.executeUpdate();
- }catch(SQLExceptione){
- e.printStackTrace();
- thrownewMySQLException();//異常向上拋
- }finally{
- SQLDBConnection.free(rs,pre,conn);
- }
- }
- publicvoiddelStu(intsid){
- Stringsql="deletestuwheres_id=?";
- conn=SQLDBConnection.getSQLDBConnection().GetConnection();
- try{
- pre=conn.prepareStatement(sql);
- pre.setInt(1,sid);
- pre.executeUpdate();
- }catch(SQLExceptione){
- e.printStackTrace();
- thrownewMySQLException();
- }finally{
- SQLDBConnection.free(rs,pre,conn);
【編輯推薦】