- 测试查询,成功输出查询结果
package com.jiuxiao.jdbc;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
/**
* 数据库连接测试
*
* @author WuDaoJiuXiao
* @Date 2022/4/20 10:42
* @since 1.0.0
*/
public class JdbcTest {
public static void main(String[] args) throws Exception {
String url = "jdbc:mysql://localhost:3306/people?useUnicode=true&characterEncoding=utf-8";
String username = "root";
String password = "0531";
//1.加载驱动
//mysql-connector-java 如果为 6.0 之上,需要用 com.mysql.cj.jdbc.Driver,之下为 com.mysql.jdbc.Driver
Class.forName("com.mysql.cj.jdbc.Driver");
//2.建立连接
Connection connection = DriverManager.getConnection(url, username, password);
//3.向数据库发送 SQL 的对象 statement
Statement statement = connection.createStatement();
//4.执行语句
String sql = "select * from student where age > 16";
ResultSet resultSet = statement.executeQuery(sql);
//5.输出结果
while (resultSet.next()) {
System.out.println("id : " + resultSet.getObject("id") + "\t"
+ "name : " + resultSet.getObject("name") + "\t"
+ "age : " + resultSet.getObject("age") + "\t"
+ "password : " + resultSet.getObject("password") + "\t"
+ "email : " + resultSet.getObject("email") + "\t"
+ "tel : " + resultSet.getObject("tel") + "\t"
);
}
//6.关闭连接,释放资源(一定要做)
resultSet.close();
statement.close();
connection.close();
}
}
标签:jdbc,java,String,resultSet,getObject,sql,2.1
From: https://www.cnblogs.com/lml66/p/18042280