欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

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();
                }
            }
        }
    }
}
相关标签: Java