欢迎来到天天文库
浏览记录
ID:34723960
大小:271.18 KB
页数:32页
时间:2019-03-10
《jsp与数据库连接jtds》由会员上传分享,免费在线阅读,更多相关内容在工程资料-天天文库。
1、与数据库连接一。Jtds建工程导入包数据库连接packageutil;importjava.sql.Connection;importjava.sql.DriverManager;importjava.sql.PreparedStatement;importjava.sql.ResultSet;importjava.sql.SQLException;publicclassDBMange{publicfinalstaticStringDRIVER="net.sourceforge.jtds.jdb
2、c.Driver";//数据库驱动publicfinalstaticStringURL="jdbc:jtds:sqlserver://localhost:1433/company";//urlpublicfinalstaticStringDBNAME="sa";//数据库用户名publicfinalstaticStringDBPASS="sa";//数据库密码/***得到数据库连接*@throwsClassNotFoundException*@throwsSQLException*@return
3、数据库连接*/publicConnectiongetConn()throwsClassNotFoundException,SQLException{Class.forName(DRIVER);//注册驱动Connectionconn=DriverManager.getConnection(URL,DBNAME,DBPASS);//获得数据库连接returnconn;//返回连接}/***释放资源*@paramconn数据库连接*@parampstmtPreparedStatement对象*@pa
4、ramrs结果集*/publicvoidcloseAll(Connectionconn,PreparedStatementpstmt,ResultSetrs){/*如果rs不空,关闭rs*/if(rs!=null){try{rs.close();}catch(SQLExceptione){e.printStackTrace();}}/*如果pstmt不空,关闭pstmt*/if(pstmt!=null){try{pstmt.close();}catch(SQLExceptione){e.prin
5、tStackTrace();}}/*如果conn不空,关闭conn*/if(conn!=null){try{conn.close();}catch(SQLExceptione){e.printStackTrace();}}}/***执行SQL语句,可以进行增、删、改的操作,不能执行查询*@paramsql预编译的SQL语句*@paramparam预编译的SQL语句中的‘?’参数的字符串数组*@return影响的条数*/publicintexecuteSQL(StringpreparedSql,S
6、tring[]param){Connectionconn=null;PreparedStatementpstmt=null;intnum=0;/*处理SQL,执行SQL*/try{conn=getConn();//得到数据库连接pstmt=conn.prepareStatement(preparedSql);//得到PreparedStatement对象if(param!=null){for(inti=0;i7、[i]);//为预编译sql设置参数}}num=pstmt.executeUpdate();//执行SQL语句}catch(ClassNotFoundExceptione){e.printStackTrace();//处理ClassNotFoundException异常}catch(SQLExceptione){e.printStackTrace();//处理SQLException异常}finally{closeAll(conn,pstmt,null);//释放资源}returnnum;}pu8、blicstaticvoidmain(String[]args){System.out.println("ok");}}方法中。声明vo(对象)dao(方法)Vopackagevo;publicclassUserInfo{intuserID;StringuserName;Stringpasswrod;publicintgetUserID(){returnuserID;}publicvoidsetUserID(intuserID){this.userID=userID;}publicStringg
7、[i]);//为预编译sql设置参数}}num=pstmt.executeUpdate();//执行SQL语句}catch(ClassNotFoundExceptione){e.printStackTrace();//处理ClassNotFoundException异常}catch(SQLExceptione){e.printStackTrace();//处理SQLException异常}finally{closeAll(conn,pstmt,null);//释放资源}returnnum;}pu
8、blicstaticvoidmain(String[]args){System.out.println("ok");}}方法中。声明vo(对象)dao(方法)Vopackagevo;publicclassUserInfo{intuserID;StringuserName;Stringpasswrod;publicintgetUserID(){returnuserID;}publicvoidsetUserID(intuserID){this.userID=userID;}publicStringg
此文档下载收益归作者所有