数据库之JDBC入门

  1. 数据表:
  2. 代码实现(注:jar包用的8.0版本)

     import java.sql.*;
     import java.util.Scanner;
    
     public class MyDatabase {
             public static void main(String[] args) {
                     Scanner sc = new Scanner(System.in);
                     System.out.print("请输入查询记录的ID:");
                     int inputid = sc.nextInt();
                     Connection con=null;
             PreparedStatement pst=null;
             ResultSet rs=null;
    
             try {
                 //1.导入驱动jar包
                 //2.注册数据库驱动
                 Class.forName("com.mysql.cj.jdbc.Driver");
                 //3.获取数据库连接对象Connection
                 con = DriverManager.getConnection("jdbc:mysql://localhost:3306/mytest","root","root");
                 //4. 定义sql
                 String sql = "select * from student where id=?";
                // 5. 获取执行sql语句的对象 PrepareStatement,并设置参数值
                pst = con.prepareStatement(sql);
                 pst.setInt(1,inputid);
                // 6. 执行sql,接受返回结果
                 rs = pst.executeQuery();
                 //7. 处理结果
                 while (rs.next())
                 {
                     int id = rs.getInt(1);
                     String name = rs.getString("name");
                     int age = rs.getInt("age");
                     System.out.println("id:"+id+",name:"+name+",age:"+age);
                 }
    
             } catch (ClassNotFoundException e) {
                 e.printStackTrace();
             } catch (SQLException e) {
                 e.printStackTrace();
             }finally {
                 //8. 释放资源
                 //避免空指针异常
                 if(rs != null){
                     try {
                         rs.close();
                     } catch (SQLException e) {
                         e.printStackTrace();
                     }
                 }
    
                 if(pst != null){
                     try {
                         pst.close();
                     } catch (SQLException e) {
                         e.printStackTrace();
                     }
                 }
    
                 if(con != null){
                     try {
                         con.close();
                     } catch (SQLException e) {
                         e.printStackTrace();
                     }
                 }
             }
         }
     }
  3. 运行结果如图:

猜你喜欢

转载自www.cnblogs.com/qujialin/p/10624764.html