本文为大家分享了java使用jdbc连接数据库的具体代码,供大家参考,具体内容如下
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
|
package com.tr.jdbc; import java.sql.connection; import java.sql.resultset; import java.sql.sqlexception; import java.sql.statement; import org.apache.commons.dbcp2.basicdatasource; public class collectionfactory { private final static string dbdriver = "com.mysql.jdbc.driver" ; private final static string dburl= "jdbc:mysql://localhost:3306/xtest?useunicode=true&characterencoding=utf-8" ; private final static string dbuser= "root" ; private final static string dbpwd= "root" ; private static basicdatasource datasource; //创建dbcp的简单数据源并初始化相关属性 static { datasource = new basicdatasource(); datasource.setdriverclassname(dbdriver); datasource.seturl(dburl); datasource.setusername(dbuser); datasource.setpassword(dbpwd); //指定数据库连接池初始化连接数 datasource.setinitialsize( 10 ); //设定同时向数据库申请的最大连接数 datasource.setmaxtotal( 50 ); //设置连接池中保持的最少连接数量 datasource.setminidle( 5 ); //其他属相...参考apache的公开文档 } //创建数据库连接对象--并且多线程并发处理(注意connection导的是java.sql的包) public static synchronized connection creatconnection(){ connection conn = null ; if (datasource!= null &&!datasource.isclosed()){ try { conn = datasource.getconnection(); } catch (sqlexception e) { e.printstacktrace(); } } return conn; } public static void main(string[] args) { string sql = "select * from s_t_user" ; connection conn = creatconnection(); statement statement = null ; resultset resultset = null ; try { statement = conn.createstatement(); resultset= statement.executequery(sql); int row = 0 ; while (resultset.next()){ row++; system.out.println( "记录行" +row+ "col2:" +resultset.getstring( 2 )); } } catch (sqlexception e) { e.printstacktrace(); } finally { if (conn!= null ) { try { conn.close(); } catch (sqlexception e) { e.printstacktrace(); } } } } } |
一定要注意不能导错包,我刚才就是因为basicdatasource的包导错了,写成了import org.apache.tomcat.dbcp.dbcp2.basicdatasource;应该是import org.apache.commons.dbcp2.basicdatasource; 而一直报这样的错误:
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。
原文链接:https://blog.csdn.net/xusheng_mr/article/details/70947768