一.pom文件的配置:
<!-- mysql driver -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.25</version>
<!-- jdbcutils -->
</dependency>
<dependency>
<groupId>commons-dbutils</groupId>
<artifactId>commons-dbutils</artifactId>
<version>1.6</version>
</dependency>
<!--- c3p0 -->
<dependency>
<groupId>com.mchange</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.5.2</version>
</dependency>
代码:
package com.meboth.hive.connection.hbase.utils;
import org.apache.commons.dbcp.BasicDataSource;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.MapListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;
import javax.sql.DataSource;
import java.util.List;
import java.util.Map;
/**
* @className JdbcUtils
* @Description TODO
* @Author admin
* @Date 2019/6/20 9:57
* @Version 1.0
**/
public class DbUtils {
private static DataSource ds;
public static final String DBDRIVER = "com.mysql.jdbc.Driver";
public static final String DBURL = "jdbc:mysql://localhost:3306/my_test";
public static final String DBUSER = "root";
public static final String DBPASS = "";
private DbUtils(){
}
public synchronized static QueryRunner getQueryRunner(){
if(ds==null){
BasicDataSource dbcpDataSource = new BasicDataSource();
dbcpDataSource.setUrl(DBURL);
dbcpDataSource.setDriverClassName(DBDRIVER );
dbcpDataSource.setUsername(DBUSER);
dbcpDataSource.setPassword(DBPASS);
dbcpDataSource.setDefaultAutoCommit(true);
dbcpDataSource.setMaxActive(100);
dbcpDataSource.setMaxIdle(30);
dbcpDataSource.setMaxWait(500);
DbUtils.ds = (DataSource)dbcpDataSource;
System.out.println("Initialize dbcp...");
}
return new QueryRunner(DbUtils.ds);
}
public static void main(String[] args) throws Exception{
QueryRunner runner = DbUtils.getQueryRunner();
Object value = runner.query("select * from company",new ScalarHandler());
List<Map<String, Object>> lists = null;
lists= runner.query("select * from company",new MapListHandler());
for(Map<String,Object> objectMap:lists){
for(String key:objectMap.keySet()){
System.out.println("key:"+key+" v:"+objectMap.get(key));
}
}
System.out.println(value);
}
}
三 结果:
Initialize dbcp...
Hello World!
key:id v:1
key:name v:阿里巴巴
key:shareholder v:马云
key:id v:2
key:name v:淘宝
key:shareholder v:马云,孙正义
key:id v:3
key:name v:baidu
key:shareholder v:liyanhong