上一篇博客我讲了如何使用JDBC对mysql数据库驱动的加载以及连接数据库,这一篇博客我来说说使用statement来对mysql数据库中的表内容进行增删改操作。
statement是Java执行数据库的一个重要的接口,用于在已经建立数据库连接的基础上,向数据库发送要执行的SQL语句。statement对象用于执行不带参数的简单SQL语句,并返回它所生成的结果对象。它的子接口为CallableStatement和PreparedStatement。statement执行过程如下图所示(百度图片):
它有很多的方法,感兴趣的同学可以到JDBC的API文档中去阅读。这里我只说几个下面操作要用到的方法。
1:void clearWarnings():返回值为空,清除在此statement对象报告上的所有警告。
2:void close():返回值为空立即释放此statement对象的数据库和JDBC资源,而不是等待该对象自动关闭时发生此操作。
3:boolean execute(String sql):返回值为boolean类型的真或者假,用于执行给定的SQL语句。
4:ResultSet executeQuery(String sql):用于执行指定sql语句,返回值为一个ResultSet对象。
5:int executeUpdate(String sql):执行给定的insert,update,delete的sql语句,返回一个int类型的值,1为成功0为失败。
6:Connection getConnection():获取生成此statement对象的Connection对象。
例子实现t_user表的内容的添加,修改,删除操作。
1:在db_user中创建表t_user。
create table t_user(
id int primary key auto_increment,
userName varchar(20),
job varchar(20),
jobTypeId int
)
2:用JDBC实现数据库驱动的加载,数据库的连接,执行SQL语句,关闭数据库连接。
/**
* 这是使用statement对数据库中的表进行增删改操作
* /
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
public class IUDData {
//数据库驱动的名字
private static String jdbcName="com.mysql.jdbc.Driver";
//数据库协议地址
private static String dbUrl = "jdbc:mysql://localhost:3306/db_user";
//数据库用户名
private static String dbUser = "root";
//数据库密码
private static String dbPassword = "panli";
//数据添加操作
private static void addData(){
try {
//加载数据库驱动
Class.forName(jdbcName);
System.out.println("数据库驱动加载成功!");
Connection conn = null;
Statement stmt = null;
try {
//连接数据库
conn = DriverManager.getConnection(dbUrl, dbUser, dbPassword);
System.out.println("数据库连接成功!");
//执行SQL语句
String sql = "insert into t_user values(null, '希拉里','总统', 1)";
stmt = conn.createStatement();
int result = stmt.executeUpdate(sql);
if(result == 1){
System.out.println("数据插入成功!");
}else{
System.out.println("数据插入失败!");
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.out.println("数据库连接失败!");
}finally{
try {
//关闭数据库
if(stmt!=null){
stmt.close();
if(conn!=null){
conn.close();
System.out.println("数据库关闭成功!");
}
}else{
System.out.println("数据库关闭失败!");
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.out.println("数据库关闭失败!");
}
}
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.out.println("数据库驱动加载失败!");
}
}
//修改数据操作
public static void updateData(){
try {
Class.forName(jdbcName);
System.out.println("数据库驱动加载成功!");
Connection conn = null;
Statement stmt = null;
try {
conn = DriverManager.getConnection(dbUrl, dbUser, dbPassword);
System.out.println("数据库连接成功!");
String sql = "update t_user set userName='希拉里', job='平民', jobTypeId = 0 where id = 24002";
stmt = conn.createStatement();
int result = stmt.executeUpdate(sql);
if(result==1){
System.out.println("数据修改成功!");
}else{
System.out.println("数据修改失败!");
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.out.println("数据库连接失败!");
}finally{
try {
//关闭数据库
if(stmt!=null){
stmt.close();
if(conn!=null){
conn.close();
System.out.println("数据库关闭成功!");
}
}else{
System.out.println("数据库关闭失败!");
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.out.println("数据库关闭失败!");
}
}
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.out.println("数据库驱动加载失败!");
}
}
//数据删除操作
private static void deleteData(){
try {
Class.forName(jdbcName);
System.out.println("数据库驱动加载成功!");
Connection conn = null;
Statement stmt = null;
try {
conn = DriverManager.getConnection(dbUrl, dbUser, dbPassword);
System.out.println("数据库连接成功!");
String sql = "delete from t_user where id = 24002";
stmt = conn.createStatement();
int result = stmt.executeUpdate(sql);
if(result == 1){
System.out.println("数据库数据删除成功!");
}else{
System.out.println("数据库数据删除失败!");
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.out.println("数据库连接失败!");
}finally{
try {
//关闭数据库
if(stmt!=null){
stmt.close();
if(conn!=null){
conn.close();
System.out.println("数据库关闭成功!");
}
}else{
System.out.println("数据库关闭失败!");
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.out.println("数据库关闭失败!");
}
}
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.out.println("数据库驱动加载失败!");
}
}
public static void main(String[] args) {
//addData();
//updateData();
deleteData();
}
}
上面的代码只是为了给初学者学习用的,在做项目时一般都不会像上面那样直接去做,而是采用Java的继承封装和多态的思想把各个功能封装在某个模块中,减少代码的重写,提高代码的利用率。下面是对上面代码的精简形式,会存在几个.java文件,存在导包。
package com.panli.model;
/**
* 对数据库表字段的建模,model模型
* @author Peter
*
*/
public class User {
private int id;
private String userName;
private String job;
private int jobTypeId;
/**
* 默认的构造方法
*/
public User() {
super();
// TODO Auto-generated constructor stub
}
/**
* 一个参数的构造方法
* @param id
*/
public User(int id) {
super();
this.id = id;
}
/**
* 带三个参数的构造方法
* @param userName
* @param job
* @param jobTypeId
*/
public User(String userName, String job, int jobTypeId) {
super();
this.userName = userName;
this.job = job;
this.jobTypeId = jobTypeId;
}
/**
* 带参数的构造方法
* @param id
* @param userName
* @param job
* @param jobTypeId
*/
public User(int id, String userName, String job, int jobTypeId) {
super();
this.id = id;
this.userName = userName;
this.job = job;
this.jobTypeId = jobTypeId;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getJob() {
return job;
}
public void setJob(String job) {
this.job = job;
}
public int getJobTypeId() {
return jobTypeId;
}
public void setJobTypeId(int jobTypeId) {
this.jobTypeId = jobTypeId;
}
}
package com.panli.dbutil;
/**
* 连接数据库
*/
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class DbUtil {
//数据库驱动名字
private static String jdbcName = "com.mysql.jdbc.Driver";
//数据库协议地址
private static String dbUrl = "jdbc:mysql://localhost:3306/db_user";
//数据库用户名
private static String dbUser = "root";
//数据库密码
private static String dbPassword = "123456";
/**
* 获取连接
* @return
* @throws Exception
*/
public static Connection getCon() throws Exception{
Class.forName(jdbcName);
Connection conn = DriverManager.getConnection(dbUrl, dbUser, dbPassword);
return conn;
}
/**
* 关闭连接
* @param stmt
* @param conn
* @throws Exception
*/
public static void close(Statement stmt,Connection conn) throws Exception{
if(stmt!=null){
stmt.close();
if(conn!=null){
conn.close();
}
}
}
/**
* 关闭连接
* @param cstmt
* @param conn
* @throws Exception
*/
public static void close(CallableStatement cstmt, Connection conn) throws Exception{
if(cstmt!=null){
cstmt.close();
if(conn!=null){
conn.close();
}
}
}
/**
* 关闭连接
* @param pstmt
* @param conn
* @throws SQLException
*/
public static void close(PreparedStatement pstmt, Connection conn) throws SQLException{
if(pstmt!=null){
pstmt.close();
if(conn!=null){
conn.close();
}
}
}
/**
* 重载关闭方法
* @param pstmt
* @param conn
* @throws Exception
*/
public void close(ResultSet rs,PreparedStatement pstmt, Connection conn) throws Exception{
if(rs!=null){
rs.close();
if(pstmt!=null){
pstmt.close();
if(conn!=null){
conn.close();
}
}
}
}
}
package com.panli.dao;
/**
* 对user表进行增删改操作
*/
import java.sql.Connection;
import java.sql.Statement;
import com.panli.dbutil.DbUtil;
import com.panli.model.User;
public class UserDao {
private static DbUtil dbUtil = new DbUtil();
//数据添加操作
public static int addData(User user) throws Exception{
Connection conn = dbUtil.getCon();
String sql = "insert into t_user values(null , '"+user.getUserName()+"','"+user.getJob()+"','"+user.getJobTypeId()+"')";
Statement stmt = conn.createStatement();
int result = stmt.executeUpdate(sql);
dbUtil.close(conn, stmt);
return result;
}
//数据修改操作
public static int updateData(User user) throws Exception{
Connection conn = dbUtil.getCon();
String sql = "update t_user set userName='"+user.getUserName()+"', job = '"+user.getJob()+"',jobTypeId = "+user.getJobTypeId()+" where id = "+user.getId();
Statement stmt = conn.createStatement();
int result = stmt.executeUpdate(sql);
dbUtil.close(conn, stmt);
return result;
}
//数据删除操作
public static int deleteData(User user) throws Exception{
Connection conn = dbUtil.getCon();
String sql = "delete from t_user where id="+user.getId();
Statement stmt = conn.createStatement();
int result = stmt.executeUpdate(sql);
dbUtil.close(conn, stmt);
return result;
}
}
package com.panli.test;
import com.panli.dao.UserDao;
import com.panli.model.User;
/**
* 测试类
* @author Peter
*
*/
public class Test {
private static UserDao userDao = new UserDao();
public static void main(String[] args) throws Exception {
/**
* 对数据表增加操作的测试
*/
/*
User user = new User("林丹", "运动员", 2);
int result = userDao.addData(user);
if(result == 1){
System.out.println("数据添加成功!");
}else{
System.out.println("数据添加失败!");
}
*/
/**
* 对数据表修改的操作
*/
/*
User user = new User(24003, "川普", "总统", 1);
int result = userDao.updateData(user);
if(result == 1){
System.out.println("数据修改成功!");
}else{
System.out.println("数据修改失败!");
}
*/
User user = new User(24004);
int result = userDao.deleteData(user);
if(result == 1){
System.out.println("数据删除成功!");
}else{
System.out.println("数据删除失败!");
}
}
}
上面就是用Statement对mysql数据库进行的增删改操作。