通过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;
    }
}

 

相关文章

连接数据库的方式:第一种方式:ODBC:开放数据库连接是微软...
JDBCRequest 使用VariableNamesmysql:数据库连接池对象var...
 1.JDBCDBC(JavaDataBaseConnectivity):Java数据库连接技术...
1.需要jar包的支持:java.sqljavax.sqlmysql-conneter-java....
1.简介Activiti是一个业务流程管理(BPM)框架,它是覆盖了业务...
1.JDBC体系系统一组规范:接口JDBC接口(API)包括两个层次:...