• 通过JDBC查询数据库中的数据


    package T3;
    
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.ResultSet;
    import java.sql.SQLException;
    import java.sql.Statement;
    
    public class StudentJDBCDemo {
        public static void main(String[] args) throws ClassNotFoundException, SQLException {
            StudentJDBCDemo demo = new StudentJDBCDemo();
            Student student = demo.findStudentById(3);
            System.out.println(student.toString()); 
        }
        
        // 通过id查询学生
        public Student findStudentById(int id) throws ClassNotFoundException, SQLException {
            // 1.注册数据库驱动
            Class.forName("com.mysql.cj.jdbc.Driver");
            // 2.与数据库建立连接
            Connection conn = DriverManager.getConnection(
                    "jdbc:mysql://@localhost:3306/student", "root", "123456");
            // 3.创建用来执行SQL语句的Statement对象
            Statement stmt = conn.createStatement();
            // 4.执行SQL语句
            String sql = "select id,name,sno,sex,birthday,cno"+
                         " from t_student"+
                         " where id="+id;
            ResultSet rs = stmt.executeQuery(sql);
            // 5.处理结果集
            Student student = null;
            if(rs.next()) {
                student = new Student(
                        rs.getInt(1), 
                        rs.getString(2), 
                        rs.getInt(3), 
                        rs.getInt(4), 
                        rs.getDate(5), 
                        rs.getInt(6));
            }
            // 6.释放资源
            if (rs != null) {
                rs.close();
            }
            if (stmt != null) {
                stmt.close();
            }
            if (conn != null) {
                conn.close();
            }
            return student;
        }
    }
  • 相关阅读:
    【递归】拆分自然数
    HDOJ3068最长回文
    博弈论——尼姆博奕
    vijos P1047最小公倍数
    Eular质数筛法-hiho一下 第九十三周
    hdoj-5652 India and China Origins二分+bfs
    hdoj-1166排兵布阵 简单的树状数组
    hdoj-5641 king's phone
    hdoj-1548简单的bfs题目
    命令中"|"的意义
  • 原文地址:https://www.cnblogs.com/alpha-cat/p/11394256.html
Copyright © 2020-2023  润新知