1)想获取连接的话需要在src下创建jdbc.properties
driverClass=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/test
user=root
pwd=abc123
2)获取数据库的连接
/*
* 要想获取数据库的连接:
* 1.导入具体数据库的驱动。在当前工程下,新建文件夹:libs,将具体数据库的.jar文件拷贝过来,然后选中右键:build path
* 2.相关数据库的服务需要开启。
* 3.获取数据库连接4个基本的信息:driverClass、url 、 user 、 password
*
* Driver:驱动
*/
/**
* 获取数据库的连接
* @return
* @throws Exception
*/
public static Connection getConnection() throws Exception {
// 1.创建Properties对象,读取配置文件中的配置信息
Properties pros = new Properties();
pros.load(JDBCUtils.class.getClassLoader()
.getResourceAsStream("jdbc.properties"));
String driverClass = pros.getProperty("driverClass");
String url = pros.getProperty("url");
String user = pros.getProperty("user");
String password = pros.getProperty("password");
// 2.加载驱动
Class.forName(driverClass);
// 3.获取连接
Connection conn = DriverManager.getConnection(url, user, password);
return conn;
}
3)关闭连接
/**
* 关闭资源
* @param ps
* @param conn
*/
public static void close(ResultSet rs ,PreparedStatement ps,Connection conn){
if(rs != null){
try {
rs.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(ps != null){
try {
ps.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(conn != null){
try {
conn.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
class ReflectionUtil{
//获取形参所对应的运行时类的父类的泛型
public static Class getSuperClassGeneric(Class clazz){//比如clazz为CustomerDAO
Type superclass = clazz.getGenericSuperclass();//superclass : DAO
ParameterizedType paramType = (ParameterizedType)superclass;
Type[] types = paramType.getActualTypeArguments();
return (Class)types[0];//Customer.class
}
}
//DAO:数据访问对象:Data Access Object
public class DAO<T> {
private Class<T> clazz = null;
public DAO(){
clazz = ReflectionUtil.getSuperClassGeneric(this.getClass());//this.getClass():CustomerDAO
}
public void m(){
System.out.println(clazz);
}
//返回特殊的值的通用的方法
public <E> E getValue(Connection conn,String sql,Object ...args){
PreparedStatement ps = null;
ResultSet rs = null;
try {
//1.
ps = conn.prepareStatement(sql);
//2.
for(int i = 0;i < args.length;i++){
ps.setObject(i + 1, args[i]);
}
//3.
rs = ps.executeQuery();
if(rs.next()){
return (E)rs.getObject(1);
}
} catch (SQLException e) {
e.printStackTrace();
}finally{
//4.
JDBCUtils.close(rs, ps, null);
}
return null;
}
//通用的查询,返回多条记录对应的一个集合
public List<T> getForList(Connection conn,String sql,Object ... args){
PreparedStatement ps = null;
ResultSet rs = null;
List<T> list = new ArrayList<T>();
try {
//1.预编译sql语句,返回一个PreparedStatement的实例
ps = conn.prepareStatement(sql);
//2.填充占位符
for(int i = 0;i < args.length;i++){
ps.setObject(i + 1, args[i]);
}
//3.执行,返回一个结果集:ResultSet
rs = ps.executeQuery();
//4.处理结果集。(难点)
//结果集的元数据:ResultSetMetaData
ResultSetMetaData rsmd = rs.getMetaData();
int columnCount = rsmd.getColumnCount();//获取了结果集的列数
while(rs.next()){
//创建一个Class对应的运行时类的对象
T t = clazz.newInstance();// new Customer(); id=0,nume=null,...
for(int i = 0;i < columnCount;i++){
Object columnVal = rs.getObject(i + 1);//获取的具体列的列值
String columnLabel = rsmd.getColumnLabel(i + 1);//获取列的别名
//通过反射装配属性值给t对象
Field field = clazz.getDeclaredField(columnLabel);
field.setAccessible(true);
field.set(t, columnVal);
}
list.add(t);
}
return list;
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
//5.关闭资源
JDBCUtils.close(rs, ps, null);
}
return null;
}
//通用的查询,返回一条记录对应的一个对象
public T getInstance(Connection conn,String sql,Object ... args){
PreparedStatement ps = null;
ResultSet rs = null;
try {
//1.预编译sql语句,返回一个PreparedStatement的实例
ps = conn.prepareStatement(sql);
//2.填充占位符
for(int i = 0;i < args.length;i++){
ps.setObject(i + 1, args[i]);
}
//3.执行,返回一个结果集:ResultSet
rs = ps.executeQuery();
//4.处理结果集。(难点)
//结果集的元数据:ResultSetMetaData
ResultSetMetaData rsmd = rs.getMetaData();
int columnCount = rsmd.getColumnCount();//获取了结果集的列数
//创建一个Class对应的运行时类的对象
T t = clazz.newInstance();// new Customer(); id=0,nume=null,...
if(rs.next()){
for(int i = 0;i < columnCount;i++){
Object columnVal = rs.getObject(i + 1);//获取的具体列的列值
String columnLabel = rsmd.getColumnLabel(i + 1);//获取列的别名
//通过反射装配属性值给t对象
Field field = clazz.getDeclaredField(columnLabel);
field.setAccessible(true);
field.set(t, columnVal);
}
return t;
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
//5.关闭资源
JDBCUtils.close(rs, ps, null);
}
return null;
}
//通用的增删改的方法
public void update(Connection conn,String sql, Object... args) {
PreparedStatement ps = null;
try {
// 1.预编译sql语句,返回一个PreparedStatement的实例
ps = conn.prepareStatement(sql);
// 2.填充占位符:?
for (int i = 0; i < args.length; i++) {
ps.setObject(i + 1, args[i]);
}
// 3.执行
ps.executeUpdate();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
// 4.关闭资源
JDBCUtils.close(ps, null);
}
}
}
对以上测试类
public class CustomerDAO extends DAO<Customer>{
public CustomerDAO(){
super();
}
/**
* 返回数据表中birth的最大值
* @param conn
* @return
*/
public Date getMaxBirth(Connection conn){
String sql = "select max(birth) from customers";
return getValue(conn, sql);
}
/**
* 返回数据表中的记录数
* @param conn
* @return
*/
public long getCount(Connection conn){
String sql = "select count(*) from customers";
return getValue(conn, sql);
}
/**
* 查询表中的所有记录
* @param conn
* @return
*/
public List<Customer> getAll(Connection conn){
String sql = "select id,name,email,birth from customers";
return getForList(conn, sql);
}
/**
* 查询表中的一条记录
* @param conn
* @param custId 指定的id
* @return
*/
public Customer getInstance(Connection conn,int custId){
String sql = "select id,name,email,birth from customers where id = ?";
return getInstance(conn, sql, custId);
}
/**
* 修改数据表中与cust的id相同的数据的信息(name,email,birth)修改为cust的相关数据
* @param conn 数据库连接
* @param cust
*/
public void update(Connection conn,Customer cust){
String sql = "update customers set name = ?,email = ?,birth = ? where id = ?";
update(conn, sql,cust.getName(),cust.getEmail(),cust.getBirth(),cust.getId());
}
/**
* 删除指定id的用户
* @param conn 数据库连接
* @param custId 要删除的用户的id
*/
public void delete(Connection conn,int custId){
String sql = "delete from customers where id = ?";
update(conn, sql, custId);
}
/**
* 向数据表中插入一条记录
* @param conn 数据库连接
* @param cust 要插入的对象
*/
public void insert(Connection conn,Customer cust){
String sql = "insert into customers(name,email,birth) values(?,?,?)";
update(conn, sql,cust.getName(),cust.getEmail(),cust.getBirth());
}
}
public class CustomerDAOTest {
CustomerDAO dao = new CustomerDAO();
@Test
public void testGeneric(){
dao.m();
}
//体现事务的针对于表的一系列的DML操作
@Test
public void testWithTransaction(){
Connection conn = null;
try {
conn = JDBCUtils.getConnection();
conn.setAutoCommit(false);
//如下的DML操作作为一个整体出现,要么都完成,要么都不完成
dao.delete(conn, 4);
Customer cust = new Customer(8, "黄成1","[email protected]",new Date(new java.util.Date().getTime()));
dao.update(conn, cust);
dao.delete(conn, 5);
conn.commit();
} catch (Exception e) {
e.printStackTrace();
try {
conn.rollback();
} catch (SQLException e1) {
e1.printStackTrace();
}
}finally{
JDBCUtils.close(null, conn);
}
}
//测试表中birth的最大值
@Test
public void testGetMaxBirth() throws Exception{
Connection conn = JDBCUtils.getConnection();
Date birth = dao.getMaxBirth(conn);
System.out.println(birth);
JDBCUtils.close(null, conn);
}
//测试表中的记录数
@Test
public void testGetCount() throws Exception{
Connection conn = JDBCUtils.getConnection();
long count = dao.getCount(conn);
System.out.println(count);
JDBCUtils.close(null, conn);
}
//测试获取所有记录
@Test
public void testGetAll() throws Exception{
Connection conn = JDBCUtils.getConnection2();
List<Customer> list = dao.getAll(conn);
JDBCUtils.close(null, conn);
for(Customer c : list){
System.out.println(c);
}
}
//修改的测试
@Test
public void testUpdate() throws Exception{
Connection conn = JDBCUtils.getConnection2();
Customer cust = new Customer(8, "黄成2","[email protected]",new Date(new java.util.Date().getTime()));
dao.update(conn, cust);
JDBCUtils.close(null, conn);
}
//删除的测试
@Test
public void testDelete() throws Exception{
Connection conn = JDBCUtils.getConnection();
dao.delete(conn, 20);
JDBCUtils.close(null, conn);
}
//测试添加的方法
@Test
public void testInsert() throws Exception{
Connection conn = JDBCUtils.getConnection();
Customer cust = new Customer(1, "黄成","[email protected]",new Date(new java.util.Date().getTime()));
dao.insert(conn, cust);
JDBCUtils.close(null, conn);
}
}