先创建一个数据库,代码如下:
create database web_test3;
use web_test3;
create table user(
id int primary key auto_increment,
username varchar(20),
password varchar(20),
nickname varchar(20),
age int
);
insert into user values(null,'aaa','123','小李',34);
insert into user values(null,'bbb','123','小黄',31);
insert into user values(null,'ccc','123','大明',30);
insert into user values(null,'ddd','123','小红',33);
在cmd下复制黏贴回车运行,如下图
1. 用Eclipse软件创建一个Java项目叫做jdbc,然后创建一个floder文件夹叫lib
2. 把你下载好的mysql-connector-java-8.0.26.jar复制到lib下面
3.对着lib右键选择Build Path添加
然后是这个样子的
然后创建一个包分一下,包里创建一个类JDBCDemo01,代码如下:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
public class JDBCDemo01 {
public static void main(String[] args) throws Exception{
//加载驱动
Class.forName("com.mysql.cj.jdbc.Driver");
//获得连接
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/web_test3", "root", "123456");
//基本操作:执行SQL
//首先获得执行SQL语句的对象
Statement s = conn.createStatement();
//编写SQL语句
String sql = "select * from user";
//执行SQL
ResultSet rs = s.executeQuery(sql);
//遍历结果集
while(rs.next()) {
System.out.print(rs.getInt("id")+" ");
System.out.print(rs.getString("username")+" ");
System.out.print(rs.getString("password")+" ");
System.out.print(rs.getString("nickname")+" ");
System.out.print(rs.getInt("age"));
System.out.println();
}
//释放资源
rs.close();
s.close();
conn.close();
}
}
运行结果如下