方法一:
结构:
MySQL数据库和表
表结构:
注:id为自增
数据库配置文件:
drive=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost/
database=student
user=root
password=123456
连接数据库jar包
把数据库的连接和关闭抽成一个工具类,这样方便后续的工作:
package com.test;
import java.sql.*;
import java.util.Properties;
public class JDBCUtil {
public static String drive;
public static String url;
public static String database;
public static String user;
public static String password;
private static Connection cn;
static {
Properties properties=new Properties();
try {
properties.load(JDBCUtil.class.getResourceAsStream("jdbc.properties"));
drive = properties.getProperty("drive");
url = properties.getProperty("url");
database = properties.getProperty("database");
user = properties.getProperty("user");
password = properties.getProperty("password");
} catch (Exception e) {
e.printStackTrace();
}
}
//连接测试
public static Connection connetion(){
try {
//注册驱动
Class.forName(drive);
//连接数据库
cn= DriverManager.getConnection
(url+database,user,password);
} catch (Exception e) {
e.printStackTrace();
}
return cn;
}
//释放资源
public static void Rease(Connection cn, Statement st, ResultSet rt){
clossCT(cn);
clossSM(st);
clossRS(rt);
}
//关闭connection连接
public static void clossCT(Connection connection){
if (connection!=null){
try {
connection.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}finally {
connection=null;
}
}
}
//关闭Statement连接
public static void clossSM(Statement st){
if (st!=null){
try {
st.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}finally {
st=null;
}
}
}
//关闭ResultSet连接
public static void clossRS(ResultSet rs){
if (rs!=null){
try {
rs.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}finally {
rs=null;
}
}
}
}
对数据库的增删改查弄成一个接口:
package imp;
import student.Stu;
import java.util.List;
public interface update {
/**
*查询所有
*/
public List<Stu> allStu();
/**
* 查询单个
*/
public Stu singleStu(in