欢迎来到天天文库
浏览记录
ID:47016436
大小:32.00 KB
页数:3页
时间:2019-05-28
《数据库连接源码》由会员上传分享,免费在线阅读,更多相关内容在行业资料-天天文库。
1、packagecom.javach08;importjava.io.FileInputStream;importjava.io.FileNotFoundException;importjava.io.IOException;importjava.io.InputStream;importjava.sql.Connection;importjava.sql.DriverManager;importjava.sql.ResultSet;importjava.sql.SQLException;importjava.sql.Statement;importjava.util.Propertie
2、s;importjavax.sql.DataSource;importorg.apache.commons.dbcp.BasicDataSourceFactory;publicclassJDBCTest2000{privatestaticDataSourcedataSource=null;/***@paramargs*/publicstaticvoidmain(String[]args){Connectioncon=null;Statementst=null;ResultSetrst=null;try{con=getConnection();//使用数据源来连接数据库st=con.cr
3、eateStatement();rst=st.executeQuery("select*fromuser_info");while(rst.next()){System.out.println(rst.getString("username"));}}catch(SQLExceptione){e.printStackTrace();}finally{if(rst!=null){try{rst.close();}catch(SQLExceptione){e.printStackTrace();}}if(st!=null){try{st.close();}catch(SQLExceptio
4、ne){e.printStackTrace();}}if(con!=null){try{con.close();}catch(SQLExceptione){e.printStackTrace();}}}}publicstaticConnectiongetConnection(){InputStreaminput=null;try{input=newFileInputStream("bin\db.properties");Propertiesproperties=newProperties();properties.load(input);if(dataSource==null){da
5、taSource=BasicDataSourceFactory.createDataSource(properties);}returndataSource.getConnection();}catch(FileNotFoundExceptione){e.printStackTrace();}catch(IOExceptione){e.printStackTrace();}catch(Exceptione){e.printStackTrace();}finally{if(input!=null){try{input.close();}catch(IOExceptione){e.prin
6、tStackTrace();}}}returnnull;}}/**下面的代码放到db.properties文件里这里用的是sqlserver2005数据库*driverClassName=com.microsoft.sqlserver.jdbc.SQLServerDriverurl=jdbc:sqlserver://localhost:1433;DataBaseName=usersusername=sapassword=123456initialSize=2maxActive=2maxWait=2000*/
此文档下载收益归作者所有