jdbc 查询语句
程序员文章站
2022-06-15 10:55:15
...
/**
* jdbc 查询语句 Student类省略
*/
import Day01.Text03.Student;
import java.sql.*;
public class Deom {
public static void main(String[] args) {
Connection conn = null;
Statement statement = null;
ResultSet resultSet = null;
try {
/**
* 注册驱动
*/
Class.forName("com.mysql.jdbc.Driver");
/**
* 获得数据库连接对象
*/
conn = DriverManager.getConnection("jdbc:mysql:///my_db", "root", "hao");
/**
* 获取执行sql对象
*/
statement = conn.createStatement();
/**
* 定义sql
*/
String sql = "select * from student";
/**
* 执行sql,并返回结果集
*/
resultSet = statement.executeQuery(sql);
/**
* 处理结果
*/
Student student = new Student();
while (resultSet.next()) {
/**
* 取数据
*/
String sno = resultSet.getString("Sno");
String sname = resultSet.getString("sname");
String ssex = resultSet.getString("Ssex");
Date sbirthday = resultSet.getDate("Sbirthday");
String sClass = resultSet.getString("SClass");
/**
* 封装数据
*/
student.setSno(sno);
student.setSname(sname);
student.setSsex(ssex);
student.setSbirthda(sbirthday);
student.setsClass(sClass);
System.out.println(student);
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} finally {
/**
* 释放资源
*/
if (resultSet != null) {
try {
resultSet.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (statement != null) {
try {
resultSet.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (conn != null) {
try {
resultSet.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
}
上一篇: 8 设计模式_工厂模式(Factory Method)
下一篇: map转实体类