一,
import java.io.IOException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.Properties;
import javax.sql.DataSource;
import org.apache.commons.dbcp.BasicDataSourceFactory;
import com.oraclewdp.util.JDBCUtils;
public class DBCPDemo {
/**
* @param args
* @throws IOException
*/
public static void main(String[] args) throws Exception {
//2、创建数据源需要的属性对象
Properties info=new Properties();
//info.setProperty(key, value);
info.load(DBCPDemo.class.getResourceAsStream("/dbcp.properties"));
//1、取得数据源对象
DataSource dataSource=BasicDataSourceFactory.createDataSource(info);
//3、从数据源取得连接
Connection connection=dataSource.getConnection();
Statement stmt=connection.createStatement();
ResultSet rs=stmt.executeQuery("select * from student");
JDBCUtils.printResult(rs);
}
}
二,连接和打印工具类
package com.oraclewdp.util;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
public class JDBCUtils {
private static final String driverClass="com.mysql.jdbc.Driver";
private static final String DB_URL="jdbc:mysql://localhost:3306/jdbctest?user=root&password=root";
// 不让别人实例化
private JDBCUtils() {
}
//驱动只需要加载一次
static{
try {
Class.forName(driverClass);
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static Connection getConnection() throws SQLException {
return DriverManager.getConnection(DB_URL);
}
public static void free(ResultSet rs,Statement stmt,Connection conn) {
if (rs!=null) {
try {
rs.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
try {
if (null != stmt) {
stmt.close();
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
if (null != conn) {
conn.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
public static void printResult(ResultSet rs) {
try {
//1、列头
ResultSetMetaData rsd=rs.getMetaData();
String spaceString="";
for (int i = 1; i <= rsd.getColumnCount(); i++) {
System.out.printf("%12s", rsd.getColumnLabel(i));
spaceString+="---------------";
}
System.err.println("\n"+spaceString);
//表内容
while (rs.next()) {
for (int i = 1; i <= rsd.getColumnCount(); i++) {
System.out.printf("%12s", rs.getObject(i));
}
System.out.println();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}