Discuss / Java / 查询

查询

Topic source

Bang

#1 Created at ... [Delete] [Delete and Lock User]
package org.example;import java.sql.*;public class ConnectedDb {    public static void main(String[] args) {        try {            // 加载JDBC驱动程序            Class.forName("com.mysql.cj.jdbc.Driver");            // 创建数据库连接            Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/learnjdbc", "root", "123456");            // 创建查询语句            String sql = "SELECT * FROM students";            // 创建一个Statement对象//            Statement stmt = conn.createStatement();            PreparedStatement ps = conn.prepareStatement("SELECT id, grade, name, gender FROM students WHERE gender=? AND grade=?");            // 执行查询语句并获取结果            ResultSet rs = ps.executeQuery(sql);            // 处理结果集            while (rs.next()) {                // 获取行数据                int id = rs.getInt("id");                String grade = rs.getString("grade");                String name = rs.getString("name");                String gender  = rs.getString("gender");                String score  = rs.getString("score");                // 输出行数据                System.out.println("ID: " + id + ", grade: " + grade+ ",name"+name+",gender "+gender +",score"+score );            }            // 关闭连接和结果集            rs.close();            ps.close();            conn.close();        } catch (Exception e) {            e.printStackTrace();        }    }}

  • 1

Reply