package com.qfedu.jdbc;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
public class TestJDBC01 {
public static void main(String[] args) throws Exception {
//加载并注册数据库驱动
Class.forName("com.mysql.cj.jdbc.Driver");
String url="jdbc:mysql://localhost:3306/chapter01?serverTimezone=GMT";
String username="root";
String password="123456";
//获取数据库连接
Connection conn=DriverManager.getConnection(url, username, password);
Statement statement=conn.createStatement();
//获取执行者对象
String sql="select * from student where sname='zhangsan'";
//执行SQ L语句
ResultSet resultSet=statement.executeQuery(sql);
System.out.println("sid|sname|age|course");
//处理结果集
while(resultSet.next()) {
int sid=resultSet.getInt("sid");
String sname=resultSet.getString("sname");
String age=resultSet.getString("age");
String course=resultSet.getString("course");
System.out.println(sid+"|"+sname+"|"+age+"|"+course);
}
resultSet.close();
statement.close();
conn.close();
}
}
MySQL:
DROP database IF EXISTS chapter01;
CREATE database chapter01;
USE chapter01;
CREATE TABLE student(
sid INT PRIMARY KEY auto_increment,
sname VARCHAR(20),
age VARCHAR(20),
course VARCHAR(20)
);
USE chapter01;
insert into student(sname,age,course) values ('zhangsan','20','Java');
insert into student(sname,age,course) values('lisi','21','Java');
insert into student(sname,age,course) values('wangwu','22','Java');
insert into student(sname,age,course) values('zhaoliu','22','Python');
insert into student(sname,age,course) values('sunqi','22','PHP');
insert into student(sname,age,course) values('zhangsansan','22','PHP');
执行结果: