准备工作:
数据库:MySQL 8.0
数据库驱动包:JDBC 9.21或8.0以上版本
编译器:IntelliJ IDEA 2022.1
在IDEA中引入JDBC的包才能正常加载数据库驱动
数据库连接
public class Connection_mysql {
public static Connection con ;
public static Connection getcon() {
try {
Class.forName("com.mysql.cj.jdbc.Driver");
System.out.println("数据库驱动加载完成");
} catch (ClassNotFoundException e) {
e.printStackTrace();
System.out.println("数据库驱动加载失败");
}
try {
String url = "jdbc:mysql://localhost:3306/java_test";
String user = "user";//这里输入用户名
String mima = "password";//这里输入密码 因发布原因变量名用来mima不是password
con = DriverManager.getConnection(url, user, mima);
System.out.println("链接数据库成功!");
return con;
} catch (SQLException e) {
e.printStackTrace();
System.out.println("链接数据库失败!!!");
}
return con;
}
}
解析:
Class.forname里面表示的是:引入的是mysql的jdbc驱动
URL是:jdbc驱动的位置因为我们引入的jdbc的包,所以url就是我们项目的地址
User和password就是你在创建数据库的时候所设置的账户名和密码,如果你没有去设置过的话,默认是root和空
Con我创建的Connection连接对象,来自java.sql.*文件因此在写代码时候要引入这个文件
DriverManager是数据库驱动对象,使用该对象的getconnection对象对数据库进行连接,其中有三个参数分别是 jdbc地址、数据库用户名、数据库密码。
数据库操作
插入
public boolean insert_student(String id, String name) {
Connection connection = Connection_mysql.getcon();
try {
Statement statement = connection.createStatement();
String sql = "insert into student values('" + id + "','" + name + "')";
int flag = statement.executeUpdate(sql);
if (flag > 0) {
return true;
} else {
return false;
}
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
删除
public boolean delete_student(String id, String name){
Connection connection=Connection_mysql.getcon();
try{
Statement statement=connection.createStatement();
String sql ="delete from student where 学号='"+id+"' and 姓名='"+name+"'";
int flag=statement.executeUpdate(sql);
if(flag>0)
{
return true;
}
else{
return false;
}
}catch(SQLException e )
{
throw new RuntimeException(e);
}
}
更新
public boolean update_student(String id, String name) {
Connection connection = Connection_mysql.getcon();
try {
Statement statement = connection.createStatement();
String sql = "update student set 学号='" + id + "', 姓名='" + name + "' where 学号='" + id + "'";
int flag = statement.executeUpdate(sql);
if (flag > 0) {
return true;
} else {
return false;
}
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
public boolean check_student(String id) {
/**
登录验证
*/
Connection connection = Connection_mysql.getcon();
try {
String sql = "select 学号 from student where 学号 =" + id + "";
Statement statement = connection.createStatement();
ResultSet resultSet = statement.executeQuery(sql);
return resultSet.next();
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
tips:
各位大佬对代码有不同意见或者有需要指正修改的,请不要吝啬,指点一下我
代码数据库表结构为