#删除mybatis_demo数据库
drop database if exists mybatis_demo;
#创建mybatis_demo数据库 create database mybatis_demo;
#使用mybatis_demo数据库
use mybatis_demo;
#创建account表
create table user (
id int auto_increment primary key,
username varchar(20),
age int,
score int
); # 新增数据
insert into user (id, username, age, score) values
(1,‘peter’, 18, 100), (2,‘pedro’, 24, 200),
(3,‘jerry’, 28, 500), (4,‘mike’, 12, 300),
(5,‘tom’, 27, 1000);
public class JDBCDemo {
public static void main(String[] args) throws Exception {
//1.注册驱动
Class.forName(“com.mysql.cj.jdbc.Driver”);
//2.获取连接
Connection connection = DriverManager.getConnection(“jdbc:mysql://localhost:3306/mybatis_demo”, “root”, “root”);
//3.获取Statement对象
PreparedStatement preparedStatement = connection.prepareStatement(“select * from user WHERE id = ?”);
preparedStatement.setInt(1, 1);
//4.执行SQL语句返回结果集
ResultSet resultSet = preparedStatement.executeQuery();
//5.遍历结果集
while (resultSet.next()) {
System.out.println("username: " + resultSet.getString(“username”));
System.out.println("age: " + resultSet.getString(“age”));
}
//6.释放资源
resultSet.close();
preparedStatement.close();
connection.close();
}
}