发布于2020-11-19 20:29 阅读(1306) 评论(0) 点赞(24) 收藏(4)
/* 加载JDBC驱动程序:反射,这样调用初始化com.mysql.jdbc.Driver类,即将该类加载到JVM方法
区,并执行该类的静态方法块、静态属性。*/
Class.forName("com.mysql.jdbc.Driver");
// 创建数据库连接
Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/students?user=root&password=zg0718&useSSL=false&useUnicode=true&characterEncoding=UTF-8");
Statement statement = connection.createStatement();
ResultSet resultSet= statement.executeQuery("select id, name, sex, age from student");
while(resultSet.next()){//遍历每一天记录
String id = resultSet.getString("id");
String name = resultSet.getString("name");
String sex = resultSet.getNString("sex");
int age = resultSet.getInt("age");
System.out.printf("id = %s,name = %s,sex = %s,age = %s%n",id,name,sex,age);
}
//逆序关闭
if(resultSet != null){
try {
resultSet.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
if (statement != null){
try {
statement.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
if (connection != null){
try {
connection.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
package test.jdbc;
import java.sql.*;
public class Main {
public static void main(String[] args) throws ClassNotFoundException, SQLException {
//1.加载jdbc驱动程序:反射,这样调用初始化com.mysql.jdbc.Driver类,即将该类加载到JVM方法区,并执行该类的静态方法块、静态属性。
Class.forName("com.mysql.jdbc.Driver");
//2.创建数据库连接
Connection connection =
DriverManager.getConnection("jdbc:mysql://localhost:3306/students?user=root&password=zg0718&useSSL=false&useUnicode=true&characterEncoding=UTF-8");
Statement statement = connection.createStatement();
//查询
ResultSet resultSet= statement.executeQuery("select id, name, sex, age from student");
//3.处理结果集
while(resultSet.next()){
String id = resultSet.getString("id");
String name = resultSet.getString("name");
String sex = resultSet.getNString("sex");
int age = resultSet.getInt("age");
System.out.printf("id = %s,name = %s,sex = %s,age = %s%n",id,name,sex,age);
}
//关闭结果集
if(resultSet != null){
try {
resultSet.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
if (statement != null){
try {
statement.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
if (connection != null){
try {
connection.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
}
作者:java大师
链接:http://www.javaheidong.com/blog/article/824/b67fe3edad169dace9b1/
来源:java黑洞网
任何形式的转载都请注明出处,如有侵权 一经发现 必将追究其法律责任
昵称:
评论内容:(最多支持255个字符)
---无人问津也好,技不如人也罢,你都要试着安静下来,去做自己该做的事,而不是让内心的烦躁、焦虑,坏掉你本来就不多的热情和定力
Copyright © 2018-2021 java黑洞网 All Rights Reserved 版权所有,并保留所有权利。京ICP备18063182号-2
投诉与举报,广告合作请联系vgs_info@163.com或QQ3083709327
免责声明:网站文章均由用户上传,仅供读者学习交流使用,禁止用做商业用途。若文章涉及色情,反动,侵权等违法信息,请向我们举报,一经核实我们会立即删除!