zoukankan      html  css  js  c++  java
  • 数据库之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. 运行结果如图:

    梦还远,路还长!
  • 相关阅读:
    (2).net体系
    (1)php开篇常识
    java基础知识-xx
    java基础知识-字符串与数组
    java基础知识-流程控制
    小明的喷漆计划
    加分二叉树
    括号序列
    P1045
    胖男孩
  • 原文地址:https://www.cnblogs.com/qujialin/p/10624764.html
Copyright © 2011-2022 走看看