JDBC
- 环境
- JDK1.8
- 第三方依赖:mysql-connector-java-8.0.15.jar
- MySQL数据库的版本与第三方依赖的版本没有关系当MySQL的版本是5,第三方依赖的版本可以用8
- 将依赖放到lib文件中,右键
add as libiary - 通过反射机制加载MySQL类驱动器:
Class.forName("com.mysql.cj.jdbc.Driver") - 创建Java与MySQL的连接通道:
DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/数据库名?useUnicode=true&characterEncoding=utf8&serverTimezone=UTC","用户名","密码"); - 创建sql语句:
- 创建传输数据的载体
conn.createStatement(); - 将sql语句放到传输通道传输
statement.executeQuery(sql);
DML(insert,update,delete),DDL(create,drop,alter) 时使用executeUpdate; 返回值是1或者0DQL(select) 时使用executeQuery 返回值是resultSet数据集合
- 对于select之后的数据存储问题
- resultSet.next()一条条获取数据
- resultSet.nextString()获取一条数据中的字段
- 将字段set到对象中,之后可以在任意的位置调用该对象
public class ShuDemo {
public static void main(String[] args) {
try {
Class.forName("com.mysql.cj.jdbc.Driver");
Connection conn = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/root?useUnicode=true&characterEncoding=utf8&serverTimezone=UTC","root","root");
String sql="select * from student";
Statement statement = conn.createStatement();
ResultSet resultSet = statement.executeQuery(sql);
List<Student> list = new ArrayList<>();
Student student = new Student();
while (resultSet.next()){
int id = resultSet.getInt("id");
String name = resultSet.getString("name");
student.setId(id);
student.setName(name);
list.add(student);
}
Student student1 = list.get(2);
System.out.println("数据 = " + student1);
} catch (Exception e) {
e.printStackTrace();
}
}
}
存储数据的对象
public class Student {
private int id;
private String name;
private boolean gender;
private String sex;
private Date date;
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
@Override
public String toString() {
return "Student{" +
"id=" + id +
", name='" + name + '\'' +
", gender=" + gender +
", sex='" + sex + '\'' +
", date=" + date +
'}';
}
}
- 常用数据类型转换表
|