jdbc
This commit is contained in:
parent
4ba14576e7
commit
a3d1677a4c
@ -7,5 +7,6 @@
|
||||
</content>
|
||||
<orderEntry type="inheritedJdk" />
|
||||
<orderEntry type="sourceFolder" forTests="false" />
|
||||
<orderEntry type="library" name="lib" level="project" />
|
||||
</component>
|
||||
</module>
|
BIN
lib/mysql-connector-java-8.0.11.jar
Executable file
BIN
lib/mysql-connector-java-8.0.11.jar
Executable file
Binary file not shown.
46
src/chapter10/Example01.java
Normal file
46
src/chapter10/Example01.java
Normal file
@ -0,0 +1,46 @@
|
||||
package chapter10;
|
||||
|
||||
import java.sql.Connection;
|
||||
import java.sql.ResultSet;
|
||||
import java.sql.Statement;
|
||||
import java.sql.DriverManager;
|
||||
|
||||
public class Example01 {
|
||||
public static void main(String[] args) {
|
||||
try {
|
||||
// 1. 加载驱动
|
||||
Class.forName("com.mysql.cj.jdbc.Driver");
|
||||
|
||||
// 2. 准备连接参数
|
||||
String url = "jdbc:mysql://localhost:3306/school?characterEncoding=utf-8&useSSL=false&serverTimezone=UTC";
|
||||
String username = "root";
|
||||
String password = "root";
|
||||
|
||||
// 使用try-with-resources自动关闭资源
|
||||
try (
|
||||
// 创建连接
|
||||
Connection connection = DriverManager.getConnection(url, username, password);
|
||||
// 创建语句对象
|
||||
Statement statement = connection.createStatement();
|
||||
// 执行查询获取结果集
|
||||
ResultSet resultSet = statement.executeQuery("select * from student")
|
||||
) {
|
||||
// 处理结果集
|
||||
while (resultSet.next()) {
|
||||
int id = resultSet.getInt("id");
|
||||
String name = resultSet.getString("name");
|
||||
int age = resultSet.getInt("age");
|
||||
String gender = resultSet.getString("gender");
|
||||
String className = resultSet.getString("class");
|
||||
|
||||
System.out.println("id=" + id + ", name=" + name + ", age=" + age +
|
||||
", gender=" + gender + ", className=" + className);
|
||||
}
|
||||
}
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
}
|
Loading…
x
Reference in New Issue
Block a user