Java实现关系型数据库工具类JdbcUtils系列二:PreparedStatement执行sql语句实现增删改
- 一、创建表
- 二、数据库工具类JdbcUtils(已实现建立连接和关闭连接)
- 三、PreparedStatement插入数据
一、创建表
CREATE TABLE `stuinfo` (
`id` int(11) NOT NULL AUTO_INCREMENT COMMENT '学生自增id',
`stunum` int(11) NOT NULL COMMENT '学号',
`name` varchar(100) NOT NULL COMMENT '姓名',
`age` int(11) NOT NULL COMMENT '年龄',
`hobby` varchar(300) NOT NULL COMMENT '爱好',
`create_time` datetime DEFAULT NULL COMMENT '创建时间',
`update_time` datetime DEFAULT NULL COMMENT '更新时间',
PRIMARY KEY (`id`),
UNIQUE KEY `uniq_stunum` (`stunum`)
) ENGINE=InnoDB AUTO_INCREMENT=9 DEFAULT CHARSET=utf8mb4 COMMENT='学生信息表';
二、数据库工具类JdbcUtils(已实现建立连接和关闭连接)
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Properties;
public class JdbcUtils {
/**
* 获取连接
* @return
* @throws IOException
* @throws ClassNotFoundException
* @throws SQLException
*/
public static Connection getConnection() throws IOException, ClassNotFoundException, SQLException {
Properties props = new Properties();
props.load(JdbcUtils.class.getClassLoader().getResourceAsStream("application" +
".properties"));
String driverClassName = props.getProperty("driverClassName");
String url = props.getProperty("url");
String user = props.getProperty("username");
String password = props.getProperty("password");
Class.forName(driverClassName);
//2.获取连接
Connection conn = DriverManager.getConnection(url, user, password);
return conn;
}
public static void release(Connection conn) throws SQLException {
if(conn != null)
conn.close();
}
public static void release(Connection conn, PreparedStatement ps) throws SQLException {
if(ps!=null) ps.close();
if(conn!=null) conn.close();
}
public static void release(Connection conn, PreparedStatement ps, java.sql.ResultSet rs) throws SQLException {
if(rs!=null) rs.close();
if(ps!=null) ps.close();
if(conn!=null) conn.close();
}
}
三、PreparedStatement插入数据
删除、修改与插入类似,只需要调整sql语句即可。
import org.junit.Test;
import java.io.IOException;
import java.sql.Connection;
import java.util.Date;
import java.sql.PreparedStatement;
import java.sql.SQLException;
/*
使用PrepareStatement完成增删改
*/
public class PrepareStatementTest {
@Test
public void test1() throws SQLException, IOException, ClassNotFoundException {
Connection conn = null;
PreparedStatement ps = null;
try{
//1.获取连接
conn = JdbcUtils.getConnection();
//2.通过当前连接,获取PrepareStatement,用于发送sql
String sql = "insert into dw.stuinfo(stunum,name,age,hobby,create_time) values(?,?,?,?,?)";
ps = conn.prepareStatement(sql);
//3.填充占位符
ps.setInt(1,100010);
ps.setString(2,"犬夜叉");
ps.setInt(3,15);
ps.setString(4,"打架");
//java.sql.Date; java.util.Date;
ps.setDate(5,new java.sql.Date(new Date().getTime()));
//4.执行sql
//返回影响行数
int row = ps.executeUpdate();
System.out.println("已影响 " + row + "行");
}catch (Exception e){
e.printStackTrace();
}finally {
JdbcUtils.release(conn,ps);
}
}
}