package chow;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import org.apache.commons.dbcp.BasicDataSource;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;
/**
* 基本的jdbc连接数据库
*
* @author Thomas
* @date 2013-07-18
*/
public class BasicJDBC {
private static BasicDataSource dataSource;
static {
ApplicationContext context = new FileSystemXmlApplicationContext(
"resource/applicationContext.xml");
dataSource = (BasicDataSource) context.getBean("DataSource");
}
public static void main(String[] args) {
Connection con = null;
String sql = "select id from table1 where name = ?";
try {
// 装入数据库特定的驱动器
Class.forName(dataSource.getDriverClassName());
// 与数据库建立连接
con = DriverManager.getConnection(dataSource.getUrl(), dataSource
.getUsername(), dataSource.getPassword());
// 使用Statement对象查询数据库
PreparedStatement ps = con.prepareStatement(sql);
int parameterIndex = 1;
ps.setString(parameterIndex, "");
//1. 执行查询,ResultSet保存查询结果
ResultSet rs = ps.executeQuery();
//2. 执行update,insert,delete语句,返回int,为影响的行数
// ps.executeUpdate();
while(rs.next()){
rs.getString("columnName");
}
//最后必须关闭ResultSet和Connection
rs.close();
con.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
配置文件:applicationContext.xml文件
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
<!-- MySQL数据库配置 -->
<bean id="DataSource" destroy-method="close" class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://location:3306/Test" />
<property name="username" value="test" />
<property name="password" value="test" />
</bean>
</beans>