一、连接数据库
a.获取数据库驱动
b.从配置文件db.properties中获取mysql
db.properties配置文件
//mysql驱动
driver:com.mysql.jdbc.Driver
//本机mysql的路径
url:jdbc:mysql://localhost:3306/jdbcdemo
//用户名
username:root
//密码
password:123
二、构建实体类
类名与数据库表名一致,字段名与数据列名一致
package bean;
public class Users {
private String username;
private String password;
private String phone;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
}
三、dbUtils类 :进行数据库的相关操作
package utils;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Properties;
import bean.Users;
/**
*
* Title:DbUtil
* Description:数据库工具类
* Company:
* @author 小桃小涛
* @date 2017年8月23日下午2:28:14
*/
public class DbUtil {
//1.获取数据库驱动
/**
* @description 获取数据库驱动
* @return
*/
public static Connection getConnection(){
Properties ps = new Properties();
Connection conn = null;
FileInputStream inputstream = null;
String driver;
String url;
String username;
String password;
try {
//从配置文件db.properties中获取mysql配置
inputstream = new FileInputStream(new File("D:\\Java Example\\Jdbc\\src\\db.properties"));
ps.load(inputstream);
driver =ps.getProperty("driver");
url =ps.getProperty("url");
username =ps.getProperty("username");
password =ps.getProperty("password");
//System.out.println(driver+" "+url+" "+username+""+password);
//加载驱动
Class.forName(driver);
conn = DriverManager.getConnection(url,username,password);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally{
//关闭流
if(inputstream!=null){
try {
inputstream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return conn;
}
//关闭资源 Object... 不定参数
public static void closeDb(Object... args){
if(args==null){
return;
}
try {
for (int i = 0; i < args.length; i++) {
//判断是不是预处理方法
if(args[i] instanceof PreparedStatement
&&args[i]!=null){
((PreparedStatement)args[i]).close();
}
//判断是不是连接
if(args[i] instanceof Connection
&&args[i]!=null){
((Connection)args[i]).close();
}
//判断是不是结果集
if(args[i] instanceof ResultSet
&&args[i]!=null){
((ResultSet)args[i]).close();
}
}
} catch (SQLException e) {
e.printStackTrace();
}
}
/**
*
* @Title: update
* @Description: TODO(更新数据)
* @param @param sql语句
* @param @param args
* @param @return 设定文件
* @return int 返回类型
* @throws
*/
public static int update(String sql,String... args){
int row=0;
//获取驱动
Connection connection = getConnection();
PreparedStatement ps =null;
try {
if(sql==null||sql.equals("")){
return row;
}else{
//sql语句预处理
ps =connection.prepareStatement(sql);
//赋值
for (int i = 0; i < args.length; i++) {
ps.setObject(i+1, args[i]);
}
row = ps.executeUpdate();
}
} catch (SQLException e) {
e.printStackTrace();
}finally{
closeDb(ps,connection);
}
return row;
}
/**
*
* @Title: getResult
* @Description: TODO(查询数据)
* @param @param cls
* @param @param sql语句
* @param @param args
* @param @return 设定文件
* @return ArrayList 返回类型
* @throws
*/
public static ArrayList getResult(Class cls,String sql,String... args){
ArrayList list = new ArrayList();
Connection connection = getConnection();
PreparedStatement ps = null;
ResultSet resultSet=null;
try {
if(sql==null||sql.equals("")){
return null;
}
ps =connection.prepareStatement(sql);
if(args!=null){
for (int i = 0; i < args.length; i++) {
ps.setObject(i+1, args[i]);
}
//执行查询方法
resultSet = ps.executeQuery();
//获取结果集结构
ResultSetMetaData metaData = resultSet.getMetaData();
//获取列数
int columnCount = metaData.getColumnCount();
while (resultSet.next()) {
T t = (T)cls.newInstance();
for (int i = 0; i < columnCount; i++) {
Object val = resultSet.getObject(i+1);
String name =metaData.getColumnLabel(i+1);
Field Field = cls.getDeclaredField(name);
//暴力反射
if(!Modifier.isPublic(Field.getModifiers())){
Field.setAccessible(true);
Field.set(t,val);
}
}
list.add(t);
}
}
} catch (SQLException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (NoSuchFieldException e) {
e.printStackTrace();
} catch (SecurityException e) {
e.printStackTrace();
} finally{
closeDb(ps,connection,resultSet);
}
return list;
}
public static void main(String[] args) {
/*String sql="UPDATE users SET username =? WHERE password=?";
int update = update(sql,"event","123","123456789");
int update = update(sql,"aaa","123");
System.out.println(update);*/
String sql="SELECT username,password,phone From users";
ArrayList result = getResult(Users.class,sql);
for (Users users : result) {
System.out.println(users.getUsername()+"\t"+users.getPassword()+"\t"+users.getPhone());
}
}
}
在上述对数据库进行增删改查的过程中,可以发现其共性部分,即通用的流程:
(1)创建Connection对象、SQL查询命令字符串;
(2)对Connection对象传入SQL查询命令,获得PreparedStatement对象;
(3)对PreparedStatement对象执行executeUpdate()或executeQurey()获得结果;
(4)先后关闭PreparedStatement对象和Connection对象。
可见,使用JDBC时,最常打交道的是Connection、PreparedStatement这两个类,以及select中的ResultSet类。