总结
JDBC接口(API)包括两个层次:
JDBC是sun公司提供一套用于数据库操作的接口,java程序员只需要面向这套接口编程即可。
不同的数据库厂商,需要针对这套接口,提供不同实现。不同的实现的集合,即为不同数据库的驱动。
————面向接口编程
补充:ODBC(Open Database Connectivity,开放式数据库连接),是微软在Windows平台下推出的。使用者在程序中只需要调用ODBC API,由 ODBC 驱动程序将调用转换成为对特定的数据库的调用请求
java.sql.Driver 接口是所有 JDBC 驱动程序需要实现的接口。这个接口是提供给数据库厂商使用的,不同数据库厂商提供不同的实现。
在程序中不需要直接去访问实现了 Driver 接口的类,而是由驱动程序管理器类
(java.sql.DriverManager)去调用这些Driver实现。
MySQL的连接URL编写方式:
Oracle 9i的连接URL编写方式:
SQLServer的连接URL编写方式:
连接方式:
@Test
public void testConnection4() {
try {
//1.数据库连接的4个基本要素:
String url = "jdbc:mysql://localhost:3306/test";
String user = "root";
String password = "abc123";
String driverName = "com.mysql.jdbc.Driver";
//2.加载驱动 (①实例化Driver ②注册驱动)
Class.forName(driverName);
//Driver driver = (Driver) clazz.newInstance();
//3.注册驱动
//DriverManager.registerDriver(driver);
/*
可以注释掉上述代码的原因,是因为在mysql的Driver类中声明有:
static {
try {
DriverManager.registerDriver(new Driver());
} catch (SQLException var1) {
throw new RuntimeException("Can't register driver!");
}
}
*/
//3.获取连接
Connection conn = DriverManager.getConnection(url, user,
password);
System.out.println(conn);
} catch (Exception e) {
e.printStackTrace();
}
}
连接方式二
@Test
public void testConnection5() throws Exception {
//1.加载配置文件
InputStream is =
ConnectionTest.class.getClassLoader().getResourceAsStream("jdbc.properties")
;
Properties pros = new Properties();
pros.load(is);
//2.读取配置信息
String user = pros.getProperty("user");
String password = pros.getProperty("password");
String url = pros.getProperty("url");
String driverClass = pros.getProperty("driverClass");
//3.加载驱动
Class.forName(driverClass);
//4.获取连接
Connection conn = DriverManager.getConnection(url,user,password);
System.out.println(conn);
}
其中配置文件声明在工程的src目录下jdbc.properties
user=root
password=abc123
url=jdbc:mysql://localhost:3306/test
driverClass=com.mysql.jdbc.Driver
说明:使用配置文件的方式保存配置信息,在代码中加载配置文件
使用配置文件的好处:
①实现了代码和数据的分离,如果需要修改配置信息,直接在配置文件中修改,不需要深入代码
②如果修改了配置信息,省去重新编译的过程。
public class StatementTest {
public static void main(String[] args) throws ClassNotFoundException, SQLException {
Class.forName("com.mysql.cj.jdbc.Driver");
Scanner sc = new Scanner(System.in);
System.out.println("请输入用户名");
String username =sc.nextLine();
System.out.println("请输入密码");
String password =sc.nextLine();
Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/test","root","root");
Statement ps = connection.createStatement();
ResultSet rs = ps.executeQuery("select user,password from user_table where user='"+username+"'and password ='"+password+"' ");
if (rs.next()){
System.out.println("登录成功!");
}else {
System.out.println("登录失败!");
}
rs.close();
ps.close();
connection.close();
}
}
public class PrepareStatementTest {
public static void main(String[] args) throws ClassNotFoundException, SQLException {
Class.forName("com.mysql.cj.jdbc.Driver");
Scanner sc = new Scanner(System.in);
System.out.println("请输入用户名");
String username =sc.nextLine();
System.out.println("请输入密码");
String password =sc.nextLine();
String sql="select user,password from user_table where user='"+username+"'and password ='"+password+"' ";
Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/test","root","root");
PreparedStatement ps = connection.prepareStatement(sql);
ResultSet rs = ps.executeQuery();
if(rs.next()){
System.out.println("登录成功");
}else{
System.out.println("登录失败");
}
rs.close();
ps.close();
connection.close();
}
}
创建表对应的实体类 ,表->类,字段->属性
Java类型 | SQL类型 |
---|---|
boolean | BIT |
byte | TINYINT |
short | SMALLINT |
int | INTEGER |
long | BIGINT |
String | CHAR,VARCHAR,LONGVARCHAR |
byte array | BINARY , VAR BINARY |
java.sql.Date | DATE |
java.sql.Time | TIME |
java.sql.Timestamp | TIMESTAMP |
Order类
public class Order {
private Integer orderId;
private String orderName;
private Date orderDate;
public Order() {
}
public Order(Integer orderId, String orderName, Date orderDate) {
this.orderId = orderId;
this.orderName = orderName;
this.orderDate = orderDate;
}
public Integer getOrderId() {
return orderId;
}
public void setOrderId(Integer orderId) {
this.orderId = orderId;
}
public String getOrderName() {
return orderName;
}
public void setOrderName(String orderName) {
this.orderName = orderName;
}
public Date getOrderDate() {
return orderDate;
}
public void setOrderDate(Date orderDate) {
this.orderDate = (java.sql.Date) orderDate;
}
@Override
public String toString() {
return "Order{" +
"orderId=" + orderId +
", orderName='" + orderName + '\'' +
", orderDate=" + orderDate +
'}';
}
}
User类
public class User{
private Integer id;
private String name;
private String password;
private String address;
private String phone;
public User() {
}
public User(Integer id, String name, String password, String address, String phone) {
this.id = id;
this.name = name;
this.password = password;
this.address = address;
this.phone = phone;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", name='" + name + '\'' +
", password='" + password + '\'' +
", address='" + address + '\'' +
", phone='" + phone + '\'' +
'}';
}
}
UserDao
public class UserDao {
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "root");
public UserDao() throws SQLException {
}
public List<User> find() throws SQLException {
ArrayList<User> list = new ArrayList<>(10);
String sql =" SELECT `id`, `name`, `password`, `address`, `phone` from user";
PreparedStatement ps = conn.prepareStatement(sql);
ResultSet rs = ps.executeQuery();
while (rs.next()){
User user = new User();
user.setId(rs.getInt(1));
user.setName(rs.getString(2));
user.setPassword(rs.getString(3));
user.setAddress(rs.getString(4));
user.setPhone(rs.getString(5));
list.add(user);
}
rs.close();
ps.close();
return list;
}
public User findOne(Integer id) throws SQLException {
User user = new User();
String sql="SELECT `id`, `name`, `password`, `address`, `phone` from user where id = ?";
PreparedStatement ps = conn.prepareStatement(sql);
ps.setInt(1, id);
ResultSet rs = ps.executeQuery();
while (rs.next()){
user.setId(rs.getInt(1));
user.setName(rs.getString(2));
user.setPassword(rs.getString(3));
user.setAddress(rs.getString("address"));
user.setPhone(rs.getString("phone"));
}
rs.close();
ps.close();
return user;
}
public int insert(User user) throws SQLException {
int rows=0;
String sql="insert into user(`name`, `password`, `address`, `phone`) values(?,?,?,?)";
PreparedStatement ps = conn.prepareStatement(sql);
ps.setString(1,user.getName());
ps.setString(2,user.getPassword());
ps.setString(3,user.getAddress());
ps.setString(4,user.getPhone());
rows = ps.executeUpdate();
ps.close();
return rows;
}
public int delete(Integer id) throws SQLException {
String sql="delete from user where id =?";
int rows=0;
PreparedStatement ps = conn.prepareStatement(sql);
ps.setInt(1,id);
rows=ps.executeUpdate();
ps.close();
return rows;
}
}
OrderDao
public class OrderDao {
/**
* `order_id`, `order_name`, `order_date`
*/
/**
* 查询所有
* @return
*/
public List<Order> find() {
List<Order> list = new ArrayList<>(10);
String sql = "SELECT `order_id`, `order_name`, `order_date` from `order`";
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
try {
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "root");
ps = conn.prepareStatement(sql);
rs = ps.executeQuery();
while (rs.next()) {
Order order = new Order();
order.setOrderId(rs.getInt(1));
order.setOrderName(rs.getString(2));
order.setOrderDate(rs.getDate(3));
list.add(order);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (rs != null && !rs.isClosed()) {
rs.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
try {
if (ps != null && !ps.isClosed()) {
ps.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
try {
if (conn != null && !conn.isClosed()) {
conn.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
return list;
}
/**
* 查询主键对应的记录
* @param id
* @return
*/
public Order get(Integer id) {
Order order = new Order();
String sql = "SELECT `order_id`, `order_name`, `order_date` from `order` where `order_id` = ?";
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
try {
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "root");
ps = conn.prepareStatement(sql);
ps.setInt(1, id);
rs = ps.executeQuery();
while (rs.next()) {
order.setOrderId(rs.getInt(1));
order.setOrderName(rs.getString(2));
order.setOrderDate(rs.getDate(3));
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (rs != null && !rs.isClosed()) {
rs.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
try {
if (ps != null && !ps.isClosed()) {
ps.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
try {
if (conn != null && !conn.isClosed()) {
conn.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
return order;
}
/**
* 添加
* @param order
* @return 返回语句影响的函数
*/
public static int insert(Order order) {
int rows = 0;
String sql = "insert into `order`( `order_name`, `order_date`) values(?,?)";
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
try {
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "root");
ps = conn.prepareStatement(sql);
ps.setString(1, order.getOrderName());
ps.setDate(2, new java.sql.Date(order.getOrderDate().getTime()));
rows = ps.executeUpdate(); //执行修改,返回语句影响的行数
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (rs != null && !rs.isClosed()) {
rs.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
try {
if (ps != null && !ps.isClosed()) {
ps.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
try {
if (conn != null && !conn.isClosed()) {
conn.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
return rows;
}
/**
* 删除
* @param id
* @return 返回语句影响的函数
*/
public int delete(Integer id) {
int rows = 0;
String sql = "delete from `order` where order_id = ?";
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
try {
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "root");
ps = conn.prepareStatement(sql);
ps.setInt(1, id);
rows = ps.executeUpdate(); //执行修改,返回语句影响的行数
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (rs != null && !rs.isClosed()) {
rs.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
try {
if (ps != null && !ps.isClosed()) {
ps.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
try {
if (conn != null && !conn.isClosed()) {
conn.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
return rows;
}
/**
* 添加
* @param order
* @return 返回语句影响的函数
*/
public int update(Order order) {
int rows = 0;
String sql = "update `order` set `order_name`=?, `order_date`=? WHERE `order_id` = ?";
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
try {
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "root");
ps = conn.prepareStatement(sql);
ps.setString(1, order.getOrderName());
ps.setDate(2, new java.sql.Date(order.getOrderDate().getTime()));
ps.setInt(3, order.getOrderId());
rows = ps.executeUpdate(); //执行修改,返回语句影响的行数
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (rs != null && !rs.isClosed()) {
rs.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
try {
if (ps != null && !ps.isClosed()) {
ps.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
try {
if (conn != null && !conn.isClosed()) {
conn.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
return rows;
}
}
格式一切按照 OrderDao这种格式 来进行异常处理
测试
ctrl+shift+T
public class UserDaoTest {
UserDao userDao = new UserDao();
@Test
public void find() {
userDao.find().forEach(u -> System.out.println(u));
}
@Test
public void get() {
System.out.println(userDao.get(4));
}
@Test
public void insert() {
User user = new User(null, "周星驰", "123", "香港", "110");
userDao.insert(user);
}
@Test
public void delete() {
userDao.delete(5);
}
@Test
public void update() {
User user = new User(1, "张学友", "123", "香港", "110");
userDao.update(user);
}
}
打开连接,关闭资源
属性文件jdbc.properties,配置连接字符串,驱动,用户,密码
user=root
password=123456
url=jdbc:mysql://localhost:3306/test
driverClass=com.mysql.cj.jdbc.Driver
JdbcUtil
public class JdbcUtil {
static String driver;
static String url;
static String user;
static String password;
static {
// InputStream in = JdbcUtil.class.getResourceAsStream("/jdbc.properties");
InputStream in = ClassLoader.getSystemClassLoader().getResourceAsStream("jdbc.properties");
Properties pro = new Properties();
try {
pro.load(in);
} catch (IOException e) {
throw new RuntimeException(e);
}
driver = pro.getProperty("driverClass");
url = pro.getProperty("url");
user = pro.getProperty("user");
password = pro.getProperty("password");
}
public static Connection getConnection() throws Exception {
Class.forName(driver);
return DriverManager.getConnection(url, user, password);
}
public static void closeResource(Connection conn, PreparedStatement ps, ResultSet rs) {
try {
if (rs != null && !rs.isClosed()) {
rs.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
try {
if (ps != null && !ps.isClosed()) {
ps.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
try {
if (conn != null && !conn.isClosed()) {
conn.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
使用
/**
* 查询所有
* @return
*/
public List<User> find() {
List<User> list = new ArrayList<>(10);
String sql = "SELECT `id`, `name`, `password`, `address`, `phone` from user";
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
try {
conn = JdbcUtil.getConnection();
ps = conn.prepareStatement(sql);
rs = ps.executeQuery();
while (rs.next()) {
User user = new User();
user.setId(rs.getInt(1));
user.setName(rs.getString(2));
user.setPassword(rs.getString(3));
user.setAddress(rs.getString("address"));
user.setPhone("phone");
list.add(user);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
JdbcUtil.closeResource(conn, ps, rs);
}
return list;
}
需要使用一个描述 ResultSet 的对象, 即 ResultSetMetaData
Dao层的基类,把Dao层重复的代码逻辑放到BaseDado中,减少开发
package B_DSCP.Dao;
import Util.JdbcUtil;
import java.lang.reflect.Field;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
public class BaseDao<T> {
Class<T> clazz;
//得到当前对象,父类声明的返回类型
{
//获取当前BaseDAO的子类继承的父类中的第一个泛型
// - this = UserDao extends BaseDao
// - this = OrderDao extends BaseDao
Type genericSuperclass = this.getClass().getGenericSuperclass();
ParameterizedType paramType = (ParameterizedType) genericSuperclass;
//获取了父类的泛型参数
Type[] typeArguments = paramType.getActualTypeArguments();
//泛型的第一个参数
clazz =(Class<T>) typeArguments[0];
}
/**
* 查询List
* @return
*/
public List<T> findList(String sql,Object... params){
ArrayList<T> list = new ArrayList<>(10);
Connection conn=null;
PreparedStatement ps =null;
ResultSet rs =null;
try {
conn = JdbcUtil.getConnection();
ps = conn.prepareStatement(sql);
//对sql语句中?这个参数进行赋值
for (int i = 0; i < params.length; i++) {
ps.setObject(i + 1, params[i]);
}
rs = ps.executeQuery();
ResultSetMetaData metaData = rs.getMetaData();
int columnCount = metaData.getColumnCount();//多少列
while (rs.next()){
T instance = clazz.newInstance();
for (int i = 0; i <columnCount ; i++) {
//列的值
Object value =rs.getObject(i+1);
String name =metaData.getColumnLabel(i+1);
Field field = clazz.getDeclaredField(name);
field.setAccessible(true);
field.set(instance,value);
}
list.add(instance);
}
} catch (Exception e){
e.printStackTrace();
}finally {
JdbcUtil.closeResource(conn,ps,rs);
}
return list;
}
public int update(String sql ,Object... params){
int rows =0;
Connection conn =null;
PreparedStatement ps = null;
ResultSet rs =null;
try {
conn =JdbcUtil.getConnection();
ps = conn.prepareStatement(sql);
for (int i = 0; i < params.length; i++) {
ps.setObject( i + 1, params[i]);
}
rows = ps.executeUpdate();
} catch (Exception e){
e.printStackTrace();
} finally {
JdbcUtil.closeResource(conn,ps,rs);
}
return rows;
}
public T findOne(String sql,Object... params){
T instance =null;
Connection conn =null;
PreparedStatement ps = null;
ResultSet rs =null;
try {
conn =JdbcUtil.getConnection();
ps =conn.prepareStatement(sql);
for (int i = 0; i < params.length; i++) {
ps.setObject( i+1,params[i]);
}
rs = ps.executeQuery();
ResultSetMetaData metaData = rs.getMetaData();
int columnCount = metaData.getColumnCount();
while (rs.next()){
instance =clazz.newInstance();
for (int i = 0; i < columnCount; i++) {
Object value =rs.getObject(i + 1);
String name =metaData.getColumnLabel(i+1);
Field field = clazz.getDeclaredField(name);
field.setAccessible(true);
field.set(instance,value);
}
}
} catch (Exception e){
e.printStackTrace();
} finally {
JdbcUtil.closeResource(conn,ps,rs);
}
return instance;
}
}
UserDao1
package B_DSCP.Dao;
import B_DSCP.po.User;
import java.util.List;
public class UserDao1 extends BaseDao<User>{
/**
* 查询所有
* @return
*/
public List<User> find() {
String sql = "SELECT `id`, `name`, `password`, `address`, `phone` from user";
return super.findList(sql);
}
/**
* 查询主键对应的记录
* @param id
* @return
*/
public User get(Integer id) {
String sql = "SELECT `id`, `name`, `password`, `address`, `phone` from user where id = ?";
return super.findOne(sql, id);
}
/**
* 添加
* @param user
* @return 返回语句影响的函数
*/
public int insert(User user) {
String sql = "insert into user(`name`, `password`, `address`, `phone`) values(?,?,?,?)";
return super.update(sql, user.getName(), user.getPassword(), user.getAddress(), user.getPhone());
}
/**
* 删除
* @param id
* @return 返回语句影响的函数
*/
public int delete(Integer id) {
String sql = "delete from user where id = ?";
return super.update(sql, id);
}
/**
* 添加
* @param user
* @return 返回语句影响的函数
*/
public int update(User user) {
String sql = "update user set `name`=?, `password`=?, `address`=?, `phone`=? WHERE `id` = ?";
return super.update(sql, user.getName(), user.getPassword(), user.getAddress(), user.getPhone(), user.getId());
}
}