JDBC例子1,首先在配置文件(system.properties)中配置上如下内容:
- 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;
- //私有构造方法
privateSQLDBConnection(){
inputstr=this.getClass().getResourceAsStream("/system.properties");
pro=newProperties();
try{
pro.load(inputstr);
}catch(IOExceptione){
e.printStackTrace();
}
try{
Class.forName(pro.getProperty("driver"));//注册驱动,只注册一次
}catch(ClassNotFoundExceptione){
e.printStackTrace();
}
}
//单例模式
publicstaticSQLDBConnectiongetSQLDBConnection(){
if(sqldb==null){
synchronized(SQLDBConnection.class){
if(sqldb==null){
sqldb=newSQLDBConnection();
}
}
}
returnsqldb;
}
//得到与数据库的连接
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的实现类
- 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);
【编辑推荐】