JDBC Statement回顾

package com.mxy.jdbc;

import java.sql.*;
import java.util.Scanner;

public class JDBCTest08 {
    
    
    public static void main(String[] args) {
    
    
        //用户在控制台输入desc就是降序,输入asc就是升序
        Scanner s = new Scanner(System.in);
        System.out.println("输入desc或asc");
        String keyWords = s.nextLine();

        //执行sql
        Connection conn = null;
        Statement stmt = null;
        ResultSet rs = null;
        try {
    
    
            //注册驱动
            Class.forName("com.mysql.jdbc.Driver");
            //获取连接
            conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/book?useUnicode=true&characterEncoding=utf8&useSSL=false","root","123456");
            
            String sql = "select prof_name from profession order by prof_name " + keyWords;
            stmt = conn.createStatement();
            //执行sql
            rs = stmt.executeQuery(sql);
            while(rs.next()){
    
    
                System.out.println(rs.getString("prof_name"));
            }
        } catch (ClassNotFoundException | SQLException e) {
    
    
            e.printStackTrace();
        }finally {
    
    
            if(rs != null){
    
    
                try {
    
    
                    rs.close();
                } catch (SQLException e) {
    
    
                    e.printStackTrace();
                }
            }
            if(stmt != null){
    
    
                try {
    
    
                    stmt.close();
                } catch (SQLException e) {
    
    
                    e.printStackTrace();
                }
            }
            if(conn != null){
    
    
                try {
    
    
                    conn.close();
                } catch (SQLException e) {
    
    
                    e.printStackTrace();
                }
            }
        }
    }
}

猜你喜欢

转载自blog.csdn.net/qq_42650433/article/details/121365134
今日推荐