Jdbc
- 概念:
- Java DataBass Connectivity Java 数据库连接, java语言操作数据库
- jdbc本质:官方定义的一套操作所有关系类型数据库的规则,即接口。各个数据库厂商去实现这个接口,提供数据库驱动jar包。我们可以使用这套接口编程,真正执行的代码时驱动jar包中的实现类
idea连接jdbc数据库操作增删改查
下载mysql-connector-java.jar包(https://www.mysql.com/)并导入
新建文件夹lib将mysql-connector-java.jar包复制粘贴到文件夹下,不要忘了导包
创建一个类 对应数据库类型,get/set方法tostring方法
public class Reg {
private int id;
private String name;
private int age;
private String identity;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getIdentity() {
return identity;
}
public void setIdentity(String identity) {
this.identity = identity;
}
@Override
public String toString() {
return "Reg{" +
"id=" + id +
", name='" + name + '\'' +
", age=" + age +
", identity='" + identity + '\'' +
'}';
}
}
定义一个类书写增删改查方法
package model;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
public class RegDao {
//新增
public void insertReg(Reg reg){
Connection conn = null;
PreparedStatement ps = null;
try {
conn=DButli.getconn();
String sql = "insert into reg(id,name,age,identity)values (?,?,?,?)";
ps = conn.prepareStatement(sql);
ps.setInt(1,reg.getId());
ps.setString(2,reg.getName());
ps.setInt(3,reg.getAge());
ps.setString(4,reg.getIdentity());
ps.execute();
conn.commit();
} catch (SQLException throwables) {
try {
conn.rollback();
} catch (SQLException e) {
e.printStackTrace();
}
throwables.printStackTrace();
} finally {
}
}
}
定义一个类书写增删改查的公共方法
package model;
import java.sql.*;
public class DButli {
private static final String URL="jdbc:mysql://localhost:3306/index";
private static final String USERNAME="账号";
private static final String PASSWORD="密码";
static {
try {
Class.forName("com.mysql.cj.jdbc");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
public static Connection getconn(){
Connection conn = null;
try{
conn = DriverManager.getConnection(URL,USERNAME,PASSWORD);
//设置mysql的数据库事务为手动提交
conn.setAutoCommit(false);
} catch (SQLException throwables) {
throwables.printStackTrace();
}
return conn;
}
public static void close(PreparedStatement ps,Connection conn){
close(null,ps,conn);
}
public static void close(ResultSet rs,PreparedStatement ps,Connection conn){
if(rs!=null){
try{
rs.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
if(ps!=null){
try{
ps.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
if(conn!=null){
try{
conn.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
}
}
调用方法
package model;
public class demo {
public static void main(String[] args) {
RegDao regDao = new RegDao();
Reg reg = new Reg();
reg.setId(1);
reg.setName("关羽");
reg.setAge(18);
reg.setIdentity("马弓手");
regDao.insertReg(reg);
}
}
刷新数据库,查看结果