实现在后台的对学生信息进行增删改查(JDBC)
1. 功能实现
运行程序控制台提示如下:
1.1 查询所有学生信息
1.2 添加学生信息
1.3 根据id修改学生信息
1.4 根据id删除学生信息
2. 代码实现
2.1 导入数据库信息
-- 1、创建数据库jt_db数据库(如果不存在才创建)
create database if not exists jt_db charset utf8;
use jt_db; -- 选择jt_db数据库
-- 2、在 jt_db 库中创建 stu 表(学生表)
drop table if exists stu;
create table stu(
stuid varchar(50),
name varchar(50),
gender char(2),
addr varchar(50),
score double
);
-- 3、往 stu 表中, 插入记录
insert into stu values("1001",'张三','男', '北京', 86);
2.2 编写JdbcUtil 工具类
package cn.tedu;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
/** JDBC工具类 */
public class JdbcUtil {
/**
* 获取数据库连接对象并返回
* @return Connection对象
* @throws Exception
*/
public static Connection getConn() throws Exception{
//1.注册驱动
Class.forName( "com.mysql.jdbc.Driver" );
//2.获取连接
Connection conn = DriverManager.getConnection(
"jdbc:mysql:///jt_db?characterEncoding=utf-8",
"root",
"root");
return conn;
}
/**
* 释放JDBC程序中的资源
* @param conn 连接对象
* @param stat 传输器对象
* @param rs 结果集对象
*/
public static void close(Connection conn,
Statement stat, ResultSet rs){
if(rs != null){
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
} finally{
rs = null;
}
}
if(stat != null){
try {
stat.close