JavaWeb-JDBC对数据进行CURD
2020-01-03 本文已影响0人
Tian_Peng
原文链接:http://www.cnblogs.com/xdp-gacl/p/3973886.html
statement对象介绍
Jdbc中的statement对象用于向数据库发送SQL语句,想完成对数据库的增删改查,只需要通过这个对象向数据库发送增删改查语句即可。
Statement对象的executeUpdate方法,用于向数据库发送增、删、改的sql语句,executeUpdate执行完后,将会返回一个整数(即增删改语句导致了数据库几行数据发生了变化)。
Statement.executeQuery方法用于向数据库发送查询语句,executeQuery方法返回代表查询结果的ResultSet对象。
CRUD操作-create
为了方便操作数据库,我们写一个JdbcUtils工具类,并且提供数据库配置文件db.properties,其中db.properties位置在src目录下,代码如下:
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://127.0.0.1:3306/jdbcStudy?autoReconnect=true&useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=CONVERT_TO_NULL&useSSL=false&serverTimezone=CTT
username=root
password=tp123456
package com.tp.utils;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;
public class JdbcUtils {
private static String driver;
private static String url;
private static String username;
private static String password;
static {
try {
//读取db.properties文件中的数据库连接信息
InputStream in = JdbcUtils.class.getClassLoader().getResourceAsStream("db.properties");
Properties prop = new Properties();
prop.load(in);
//获取数据库连接驱动
driver = prop.getProperty("driver");
//获取数据库连接URL地址
url = prop.getProperty("url");
//获取数据库连接用户名
username = prop.getProperty("username");
//获取数据库连接密码
password = prop.getProperty("password");
//加载数据库驱动
Class.forName(driver);
} catch (Exception e) {
throw new ExceptionInInitializerError(e);
}
}
/**
* @return Connection 数据库连接对象
* @throws SQLException
* @Method: getConnection
* @Description: 获取数据库连接对象
* @Anthor:TP
*/
public static Connection getConnection() throws SQLException {
return DriverManager.getConnection(url, username, password);
}
/**
* @param conn 数据库连接对象
* @param st Statement
* @param rs rs
* @Method: release
* @Description: 释放资源
* 要释放的资源包括Connection数据库连接对象,负责执行SQL命令的Statement对象,存储查询结果的ResultSet对象
* @Anthor:TP
*/
public static void release(Connection conn, Statement st, ResultSet rs) {
if (rs != null) {
try {
//关闭存储查询结果的ResultSet对象
rs.close();
} catch (Exception e) {
e.printStackTrace();
}
}
if (st != null) {
try {
//关闭负责执行SQL命令的Statement对象
st.close();
} catch (Exception e) {
e.printStackTrace();
}
}
if (conn != null) {
try {
//关闭Connection数据库连接对象
conn.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
新建测试类
使用executeUpdate(String sql)方法完成数据添加操作,示例操作:
@Test
public void jdbcCreateTest() {
Connection conn = null;
Statement st = null;
ResultSet rs = null;
try {
//获取一个数据库连接
conn = JdbcUtils.getConnection();
//通过conn对象获取负责执行SQL命令的Statement对象
st = conn.createStatement();
//要执行的SQL命令
String sql = "insert into user(name,password,email,birthday) values('mayun','123','mayun@aliaba.com','1964-09-10')";
//执行插入操作,executeUpdate方法返回成功的条数
int num = st.executeUpdate(sql);
System.out.println(">>>>num:" + num);
if (num > 0) {
System.out.println("插入成功!!");
}
} catch (Exception e) {
e.printStackTrace();
} finally {
//SQL执行完成之后释放相关资源
JdbcUtils.release(conn, st, rs);
}
}
CRUD操作-update
使用executeUpdate(String sql)方法完成数据修改操作,示例操作:
@Test
public void jdbcUpdateTest(){
Connection conn = null;
Statement st = null;
ResultSet rs = null;
try {
//获取一个数据库连接
conn = JdbcUtils.getConnection();
//通过conn对象获取负责执行SQL命令的Statement对象
st = conn.createStatement();
//要执行的SQL命令
String sql = "update user set name = 'xiaoyunyun' where name = 'mayun'";
//执行修改操作,executeUpdate方法返回成功的条数
int num = st.executeUpdate(sql);
System.out.println(">>>>num:" + num);
if (num > 0) {
System.out.println("插入成功!!");
}
} catch (Exception e) {
e.printStackTrace();
} finally {
//SQL执行完成之后释放相关资源
JdbcUtils.release(conn, st, rs);
}
}
CRUD操作-delete
使用executeUpdate(String sql)方法完成数据删除操作,示例操作:
@Test
public void jdbcDeleteTest() {
Connection conn = null;
Statement st = null;
ResultSet rs = null;
try {
//获取一个数据库连接
conn = JdbcUtils.getConnection();
//通过conn对象获取负责执行SQL命令的Statement对象
st = conn.createStatement();
//要执行的SQL命令
String sql = "delete from user where name = 'xiaoyunyun'";
//执行删除操作,executeUpdate方法返回成功的条数
int num = st.executeUpdate(sql);
System.out.println(">>>>num:" + num);
if (num > 0) {
System.out.println("删除成功!!");
}
} catch (Exception e) {
e.printStackTrace();
} finally {
//SQL执行完成之后释放相关资源
JdbcUtils.release(conn, st, rs);
}
}
CRUD操作-read
使用executeQuery(String sql)方法完成数据查询操作,示例操作:
@Test
public void jdbcReadTest() {
Connection conn = null;
Statement st = null;
ResultSet rs = null;
try {
conn = JdbcUtils.getConnection();
String sql = "select * from user where id=3";
st = conn.createStatement();
rs = st.executeQuery(sql);
List<User> userList = new ArrayList<>();
while (rs.next()) {
User user = new User();
user.setId(rs.getInt("id"));
user.setName(rs.getString("name"));
user.setPassword(rs.getString("password"));
user.setEmail(rs.getString("email"));
user.setBirthday(rs.getDate("birthday"));
userList.add(user);
}
System.out.println(userList);
} catch (Exception e) {
e.printStackTrace();
} finally {
JdbcUtils.release(conn, st, rs);
}
}
PreparedStatement对象介绍
PreperedStatement是Statement的子类,它的实例对象可以通过调用Connection.preparedStatement()
方法获得,相对于Statement对象而言:
PreparedStatement的优点:
- PreperedStatement可以避免SQL注入的问题。
- Statement会使数据库频繁编译SQL,可能造成数据库缓冲区溢出。
- PreparedStatement可对SQL进行预编译,从而提高数据库的执行效率。
- 并且PreperedStatement对于sql中的参数,允许使用占位符的形式进行替换,简化sql语句的编写。
代码示例:
public class JdbcCURDTestByPreparedStatement {
@Test
public void insert() {
Connection conn = null;
PreparedStatement st = null;
ResultSet rs = null;
try {
//获取一个数据库连接
conn = JdbcUtils.getConnection();
//要执行的SQL命令,SQL中的参数使用?作为占位符
String sql = "insert into user(name,password,email,birthday) values(?,?,?,?)";
//通过conn对象获取负责执行SQL命令的prepareStatement对象
st = conn.prepareStatement(sql);
//为SQL语句中的参数赋值,注意,索引是从1开始的
st.setString(1, "mahuateng");//name是varchar(字符串类型)
st.setString(2, "654321");//password是varchar(字符串类型)
st.setString(3, "mahuateng@qq.com");//email是varchar(字符串类型)
st.setDate(4, new java.sql.Date(new Date().getTime()));//birthday是date类型
//执行插入操作,executeUpdate方法返回成功的条数
int num = st.executeUpdate();
System.out.println(">>>>num:" + num);
if (num > 0) {
System.out.println("插入成功!!");
}
} catch (Exception e) {
e.printStackTrace();
} finally {
//SQL执行完成之后释放相关资源
JdbcUtils.release(conn, st, rs);
}
}
@Test
public void delete() {
Connection conn = null;
PreparedStatement st = null;
ResultSet rs = null;
try {
conn = JdbcUtils.getConnection();
String sql = "delete from user where id=?";
st = conn.prepareStatement(sql);
st.setInt(1, 1);
int num = st.executeUpdate();
System.out.println(">>>>num:" + num);
if (num > 0) {
System.out.println("删除成功!!");
}
} catch (Exception e) {
e.printStackTrace();
} finally {
JdbcUtils.release(conn, st, rs);
}
}
@Test
public void update() {
Connection conn = null;
PreparedStatement st = null;
ResultSet rs = null;
try {
conn = JdbcUtils.getConnection();
String sql = "update user set name=?,email=? where id=?";
st = conn.prepareStatement(sql);
st.setString(1, "tp");
st.setString(2, "tp@163.com");
st.setInt(3, 2);
int num = st.executeUpdate();
System.out.println(">>>>num:" + num);
if (num > 0) {
System.out.println("更新成功!!");
}
} catch (Exception e) {
e.printStackTrace();
} finally {
JdbcUtils.release(conn, st, rs);
}
}
@Test
public void find() {
Connection conn = null;
PreparedStatement st = null;
ResultSet rs = null;
try {
conn = JdbcUtils.getConnection();
String sql = "select * from user where id=?";
st = conn.prepareStatement(sql);
st.setInt(1, 2);
rs = st.executeQuery();
if (rs.next()) {
System.out.println(rs.getString("name"));
}
} catch (Exception e) {
} finally {
JdbcUtils.release(conn, st, rs);
}
}
}