数据库:mysql。
语法 select * from table_name limit start, count;
start和count 类型是int。
start 从什么位置开始查询。
count 查询的记录(行)数。
如 select * from table_name limit 5,10;
表示从表中第5个记录开始(不包括第五个记录)查询10条记录;
创建表:
CREATE TABLE `hero` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(20) DEFAULT NULL,
`hp` float DEFAULT NULL,
`damage` int(11) DEFAULT NULL,
PRIMARY KEY (`id`)
)
在代码中插入1000条数据
上代码
import java.sql.*;
import java.util.Scanner;
public class TestJDBC7 {
//是否初始化表数据的判断
private static boolean data = true;
public static void main(String[] args) {
//加载mysql驱动
try {
//mysql 8.0以后的驱动为com.mysql.cj.jdbc.Driver, 而不是com.mysql.jdbc.Driver
Class.forName("com.mysql.cj.jdbc.Driver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
Scanner in = new Scanner(System.in);
System.out.println("每页显示5条记录,请问你想查询第几页!");
//一个while让程序持续运行,可以不断的进行新的查询。
while(true) {
//读取想要查询第几页
int pageNUmber = in.nextInt();
pageList(pageNUmber);
}
}
public static void pageList(int number) {
//逻辑判断,使得start和count变成 select * from table_name limit start,count;
//中我们想要的值;
int start = 0;
int count = 5;
if (number == 1) {
start = 0;
}
else {
if (number < 1)
System.out.println("输入错误! 请再次输入大于等于1的整数!");
else {
start = (number - 1) * 5;
}
}
//连接你自己的数据库
try(Connection c = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/how2java?" +
"serverTimezone=GMT%2B8&&useSSL=false",
"root","cbytest0317");
Statement s = c.createStatement()) {
String sql1 = "truncate table hero";
String sql2 = "select * from hero limit " + start + "," + count;
String sql3 = "insert into hero values(null,'阳光',666, 99)";
if (data) {
//此时表hero还没有数据我们插入1000条记录;
System.out.println("初始化数据库!");
s.execute(sql1);
for (int i = 0; i < 1000; i++) {
s.execute(sql3);
}
//插入记录后数据库已有数据,不在初始化表数据。
data = false;
}
ResultSet rs = s.executeQuery(sql2);
System.out.printf("%s\t\t%s\t\t%s\t\t%s\n","id", "name", "hp", "damage");
while(rs.next()) {
int id = rs.getInt(1);
String name = rs.getString(2);
float hp = rs.getFloat(3);
int damage = rs.getInt(4);
//输出查询结果
System.out.printf("%d\t\t%s\t\t%.0f\t\t%d\n",id,name, hp, damage);
}//不必关闭Connection和Statement, try块结束后 会自动关闭,而ResultSet
//会在Statement关闭时自动关闭!这种写法必须把Connection和Statement写在
//try(){} 的圆括号内;否则要在最后用finally进行关闭。
} catch (SQLException e) {
e.printStackTrace();
}
}
}
看看运行结果,代码向表需插入数据需要等待一会。