首先jdbc是规范各个数据库厂商的一个统一的API,只要加载不同的驱动Driver,就可以使用同一种语法去操作数据库
前期准备:一个user表,表结字段:id,user_name,user_id
正式开始
未处理异常的读取操作基本步骤
import java.sql.*;
/**
* jdbc基本操作步骤
*/
public class JdbcDemo1 {
static String url = "day04.jdbc:mysql://127.0.0.1:3306/course?serverTimezone = GMT";
static String userName = "root";
static String password = "";
public static void main(String[] args) throws SQLException {
// 1.基于url+userName+password 从驱动管理器中拿到MySql的连接 , 建立连接
Connection connection = DriverManager.getConnection(url, userName, password);
// 2.基于连接,建立与数据库的操作, statement
String sql = "select * from tb_user";
PreparedStatement statement = connection.prepareStatement(sql);
// 3.基于创建好的statement 发起对应的数据库操作, 增删改查,CRUD
// 发起查询时,查询的结果会被封装进 ResultSet 类中
ResultSet resultSet = statement.executeQuery();
// 4.解析结果集
while (resultSet.next()) {
// 基于列名或列的索引,取出每列的数值,注意:如果用的是索引法,记得是从1开始的
int id1 = resultSet.getInt(1);
int id2 = resultSet.getInt("id");
String name1 = resultSet.getString(2);
String name2 = resultSet.getString("user_name");
int age1 = resultSet.getInt(3);
int age2 = resultSet.getInt("user_id");
String row = String.format("id1=%d,id2=%d,name1=%s,name2=%s,age1=%d,age2=%d"
, id1, id2, name1, name2, age1, age2);
System.out.println(row);
}
// 5.资源关闭,记得倒叙关闭
resultSet.close();
statement.close();
connection.close();
}
}
未处理异常的写入(包含insert,update,delete)操作的基本步骤
import java.sql.*;
/**
* 插入操作
*/
public class JdbcDemo4 {
static String url = "day04.jdbc:mysql://127.0.0.1:3306/course?serverTimezone = GMT";
static String userName = "root";
static String password = "";
public static void main(String[] args) throws SQLException {
Connection connection = DriverManager.getConnection(url, userName, password);
String sql = "insert into tb_user(id,user_name,user_id) values (200,‘zhangsan‘,24)";
PreparedStatement statement = connection.prepareStatement(sql);
int effectRows = statement.executeUpdate();
System.out.println("effectRows = " + effectRows);
statement.close();
connection.close();
}
}
总结:
关键字:DriverManager.getConnection(url,name,password) , connection.prepareStatement(sql) , statement.executeQuery()(executeUpdate) , resultSet.getInt(getString)