构建spring+dbcp连接池+sqlite

构建spring+dbcp连接池+sqlite 2012-03-12 10:30:58

分类: Java

我这两周在开发公司自己的搜索引擎,主要是用lucene,配置数据我设计是用sqlite,所有的配置通过spring进行串联
1.准备jar包
http://files.zentus.com/sqlitejdbc/sqlitejdbc-v056.jar
spring.jar
commons-pool.jar
commons-logging.jar
commons-dbcp.jar
2.导入jar包到工程里
3.创建数据库操作类

点击(此处)折叠或打开

  1. package com.search.util;

  2. import java.sql.Connection;
  3. import java.sql.PreparedStatement;
  4. import java.sql.ResultSet;
  5. import java.sql.SQLException;
  6. import java.sql.Statement;


  7. import org.apache.commons.dbcp.BasicDataSource;


  8. /**
  9. * 连接和使用数据库资源的工具类
  10. *
  11. * @author yifangyou
  12. * @version search 2012-03-12
  13. */
  14. public class DatabaseSqliteUtil {

  15. /**
  16. * 数据源
  17. */
  18. private BasicDataSource dataSource;

  19. /**
  20. * 数据库连接
  21. */
  22. public Connection conn;

  23. /**
  24. * 获取数据源
  25. * @return 数据源
  26. */
  27. public BasicDataSource getDataSource() {
  28. return dataSource;
  29. }

  30. /**
  31. * 设置数据源
  32. * @param dataSource 数据源
  33. */
  34. public void setDataSource(BasicDataSource dataSource) {
  35. this.dataSource = dataSource;
  36. }


  37. /**
  38. * 获取数据库连接
  39. * @return conn
  40. */
  41. public Connection getConnection() {
  42. try {
  43. conn = dataSource.getConnection();
  44. } catch (Exception e) {
  45. e.printStackTrace();
  46. return null;
  47. }
  48. return conn;
  49. }

  50. /**
  51. * 关闭数据库连接
  52. * @param conn
  53. */
  54. public static void closeConnection(Connection conn) {
  55. if (null != conn) {
  56. try {
  57. conn.close();
  58. conn = null;
  59. } catch (SQLException e) {
  60. e.printStackTrace();
  61. }
  62. }
  63. }

  64. /**
  65. * 获取执行SQL的工具
  66. * @param conn 数据库连接
  67. * @return stmt
  68. */
  69. public static int getFoundRows(Connection conn) {
  70. Statement stmt=null;
  71. ResultSet rs=null;
  72. try {
  73. stmt=getStatement(conn);
  74. rs=stmt.executeQuery("SELECT FOUND_ROWS()");
  75. if(rs.next()){
  76. return rs.getInt(1);
  77. }
  78. } catch (SQLException e) {
  79. e.printStackTrace();
  80. }finally{
  81. closeStatement(stmt);
  82. closeResultSet(rs);
  83. }
  84. return 0;
  85. }

  86. /**
  87. * 获取执行SQL的工具
  88. * @param conn 数据库连接
  89. * @return stmt
  90. */
  91. public static Statement getStatement(Connection conn) {
  92. Statement stmt = null;
  93. try {
  94. stmt = conn.createStatement();
  95. } catch (SQLException e) {
  96. e.printStackTrace();
  97. }

  98. return stmt;
  99. }

  100. /**
  101. * 获取执行SQL的工具
  102. * @param conn 数据库连接
  103. * @param sql SQL语句
  104. * @return prepStmt
  105. */
  106. public static PreparedStatement getPrepStatement(Connection conn, String sql) {
  107. PreparedStatement prepStmt = null;
  108. try {
  109. prepStmt = conn.prepareStatement(sql);
  110. } catch (SQLException e) {
  111. e.printStackTrace();
  112. }
  113. return prepStmt;
  114. }

  115. /**
  116. * 关闭数据库资源
  117. * @param stmt
  118. */
  119. public static void closeStatement(Statement stmt) {
  120. if (null != stmt) {
  121. try {
  122. stmt.close();
  123. stmt = null;
  124. } catch (SQLException e) {
  125. e.printStackTrace();
  126. }
  127. }
  128. }

  129. /**
  130. * 关闭数据库资源
  131. * @param prepStmt
  132. */
  133. public static void closePrepStatement(PreparedStatement prepStmt) {
  134. if (null != prepStmt) {
  135. try {
  136. prepStmt.close();
  137. prepStmt = null;
  138. } catch (SQLException e) {
  139. e.printStackTrace();
  140. }
  141. }
  142. }

  143. /**
  144. * 获取结果集
  145. * @param stmt 执行SQL的工具
  146. * @param sql SQL语句
  147. * @return 结果集
  148. */
  149. public static ResultSet getResultSet(Statement stmt, String sql) {
  150. ResultSet rs = null;
  151. try {
  152. rs = stmt.executeQuery(sql);
  153. } catch (SQLException e) {
  154. e.printStackTrace();
  155. }
  156. return rs;
  157. }

  158. /**
  159. * 关闭数据库资源
  160. * @param rs
  161. */
  162. public static void closeResultSet(ResultSet rs) {
  163. if (null != rs) {
  164. try {
  165. rs.close();
  166. rs = null;
  167. } catch (SQLException e) {
  168. e.printStackTrace();
  169. }
  170. }
  171. }
  172. public static Boolean setAutoCommit(Connection conn,boolean commitStatus){
  173. if(conn==null){
  174. return true;
  175. }
  176. try {
  177. boolean commit = conn.getAutoCommit();
  178. conn.setAutoCommit(commitStatus);
  179. return commit;
  180. } catch (SQLException e1) {
  181. e1.printStackTrace();
  182. return true;
  183. }
  184. }
  185. public static boolean rollback(Connection conn,boolean oldCommitStatus){
  186. if(conn==null){
  187. return true;
  188. }
  189. try {
  190. conn.rollback(); // 事物回滚
  191. conn.setAutoCommit(oldCommitStatus);
  192. return true;
  193. } catch (SQLException e1) {
  194. e1.printStackTrace();
  195. return false;
  196. }
  197. }
  198. public static boolean commit(Connection conn,boolean oldCommitStatus){
  199. if(conn==null){
  200. return true;
  201. }
  202. try {
  203. conn.commit(); // 事物回滚
  204. conn.setAutoCommit(oldCommitStatus);
  205. return true;
  206. } catch (SQLException e1) {
  207. e1.printStackTrace();
  208. return false;
  209. }
  210. }
  211. public static int getLastId(PreparedStatement ps){
  212. ResultSet rs=null;
  213. try {
  214. rs = ps.getGeneratedKeys();
  215. if (rs != null&&rs.next()) {
  216. return rs.getInt(1);
  217. }
  218. } catch (SQLException e) {
  219. // TODO Auto-generated catch block
  220. e.printStackTrace();

  221. }finally{
  222. closeResultSet(rs);
  223. }
  224. return -1;
  225. }
  226. /**
  227. * 判断是否是管理员
  228. * @param conn mysql连接
  229. * @param ip 请求ip
  230. * @param password 管理员密码
  231. * @author yaofuyuan
  232. * @since 2011-08-02 12:58:00
  233. * @return void 0:不是,1:是,-1:数据库出错
  234. */
  235. public int isSuperAdmin(Connection conn,String ip,String password){
  236. if(conn==null){
  237. return -1;
  238. }
  239. PreparedStatement ps =getPrepStatement(
  240. conn,
  241. "select count(*) as count from auth_admin_server where ip=? and password=?");
  242. ResultSet rs = null;
  243. try {
  244. // 查询帐号,用户名和密码
  245. ps.setString(1, ip);
  246. ps.setString(2, password);
  247. rs=ps.executeQuery();
  248. if (rs.next()) {
  249. if(rs.getInt("count")==0){
  250. //用户名密码错误
  251. return 0;
  252. }else{
  253. return 1;
  254. }
  255. }
  256. return -1;
  257. }
  258. catch(Exception e){
  259. e.printStackTrace();
  260. return -1;
  261. }finally{
  262. closeResultSet(rs);
  263. closePrepStatement(ps);
  264. }

  265. }


  266. public int test(Connection conn){

  267. PreparedStatement pst =getPrepStatement(conn, "select 123");
  268. // 获取结果集
  269. ResultSet rs = null;
  270. try {
  271. rs = pst.executeQuery();
  272. if (rs.next()) {
  273. return rs.getInt(1);
  274. }
  275. } catch (SQLException e) {
  276. e.printStackTrace();
  277. } finally {
  278. // 关闭数据库资源
  279. closeResultSet(rs);
  280. closePrepStatement(pst);
  281. }

  282. return -1;
  283. }


  284. }

2.创建applicationContent.xml

点击(此处)折叠或打开

  1. <?xml version="1.0" encoding="UTF-8"?>

  2. <!--
  3.   - Application context definition for JPetStore's business layer.
  4.   - Contains bean references to the transaction manager and to the DAOs in
  5.   - dataAccessContext-local/jta.xml (see web.xml's "contextConfigLocation").
  6.   -->
  7. <beans xmlns="http://www.springframework.org/schema/beans"
  8.         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  9.         xmlns:aop="http://www.springframework.org/schema/aop"
  10.         xmlns:tx="http://www.springframework.org/schema/tx"
  11.         xsi:schemaLocation="
  12.             http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
  13.             http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
  14.             http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">
  15.  
  16.       <!-- =================================== 配置Spring数据源 ========================================= -->
  17.         <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
  18.             destroy-method="close">
  19.         <property name="driverClassName" value="org.sqlite.JDBC" />
  20.         <property name="url" value="jdbc:sqlite:search.db" />
  21.         <property name="maxIdle" value="10"/>
  22.         <property name="maxActive" value="100"/>
  23.         <property name="maxWait" value="10000"/>
  24.         <property name="validationQuery" value="select 1"/>
  25.         <property name="testOnBorrow" value="false"/>
  26.         <property name="testWhileIdle" value="true"/>
  27.         <property name="timeBetweenEvictionRunsMillis" value="1200000"/>
  28.         <property name="minEvictableIdleTimeMillis" value="1800000"/>
  29.         <property name="numTestsPerEvictionRun" value="5"/>
  30.         <property name="defaultAutoCommit" value="true"/>
  31.     </bean>
  32.     <!--
  33.         BasicDataSource提供了close()方法关闭数据源,所以必须设定destroy-method=”close”属性,
  34.         以便Spring容器关闭时,数据源能够正常关闭。除以上必须的数据源属性外,
  35.          还有一些常用的属性:
  36.         defaultAutoCommit:设置从数据源中返回的连接是否采用自动提交机制,默认值为 true;
  37.         defaultReadOnly:设置数据源是否仅能执行只读操作, 默认值为 false;
  38.         maxActive:最大连接数据库连接数,设置为0时,表示没有限制;
  39.         maxIdle:最大等待连接中的数量,设置为0时,表示没有限制;
  40.         maxWait:最大等待秒数,单位为毫秒, 超过时间会报出错误信息;
  41.         validationQuery:用于验证连接是否成功的查询SQL语句,SQL语句必须至少要返回一行数据,
  42.                           如你可以简单地设置为:“select count(*) from user”;
  43.         removeAbandoned:是否自我中断,默认是 false ;
  44.         removeAbandonedTimeout:几秒后数据连接会自动断开,在removeAbandoned为true,提供该值;
  45.         logAbandoned:是否记录中断事件, 默认为 false;
  46.      -->
  47.     <bean id="databaseUtil" class="com.search.util.DatabaseSqliteUtil">
  48.         <property name="dataSource" ref="dataSource" />
  49.     </bean>
  50.     
  51.     
  52.         <bean id="Main" class="com.search.main.Main" scope="prototype">
  53.             <property name="databaseUtil" ref="databaseUtil" />
  54.         </bean>     
  55. </beans>
4.使用

点击(此处)折叠或打开

  1. package com.search.main;

  2. import java.sql.Connection;

  3. import org.springframework.context.ApplicationContext;
  4. import org.springframework.context.support.FileSystemXmlApplicationContext;
  5. import org.springframework.context.support.ClassPathXmlApplicationContext;

  6. import com.search.tool.Spider;
  7. import com.search.util.DatabaseSqliteUtil;


  8. public class Main {
  9.     
  10.     public static void main(String[] args) {

  11.         ApplicationContext beanFactory=new FileSystemXmlApplicationContext("D:/workspace/lucene-3.5.0/cn_applicationContext.xml");
  12.         DatabaseSqliteUtil databaseUtil=(DatabaseSqliteUtil)beanFactory.getBean("databaseUtil");
  13.         Connection conn=databaseUtil.getConnection();
  14.         System.out.println(databaseUtil.test(conn));
  15.         DatabaseSqliteUtil.closeConnection(conn);
  16.         
  17. //        Spider ph = new Spider("http://www.test.dev");
  18. //        ph.openWriteIndexDB("D:/workspace/lucene-3.5.0/search-db");
  19. //        try {
  20. //            //ph.processHtml();
  21. //            //Thread search = new Thread(ph);
  22. //            //search.start();// 启动线程
  23. //            ph.crawl(ph.getLinklist());
  24. //        } catch (Exception ex) {
  25. //
  26. //        }
  27. //        ph.closeWriteIndexDB();
  28.         //search();
  29.     }
  30. }
执行结果
构建spring+dbcp连接池+sqlite_第1张图片
end

你可能感兴趣的:(Java)