JDBC小程序--实现命令行SQL语句命令

import java.sql.*;
import java.io.*;

public class DBTools
{
 public static void main(String[] args){
   //1.连接任意数据库
   Connection con = getConnection();
   if(con==null){
     System.out.println("连接为null");
  return;
   }
   //2.处理用户命令
   process(con);
   //3.清理
   JdbcUtil.close(null,null,con);
   System.out.println("再见,欢迎下次使用");
 }
 public static void process(Connection con){
   boolean flag = true;
   while(flag){
      String command = getCommand();
   if("quit".equals(command)){
     flag=false;
   }else{
     processSQL(con,command);
   }
   }
 }
 public static Connection getConnection(){//连接数据库
   String url = prompt("请输入URL:");
   String userName = prompt("请输入用户名:");
   String pwd = prompt("请输入密码:");
   Connection con = null;
   try{
     con = DriverManager.getConnection(
        url,userName,pwd);
   }catch(Exception e){
     System.out.println(e.getMessage());
   }
   return con;
 }
    public static String getCommand(){//输入指令
   String message = "->";
   String command = "";
   StringBuffer sb = new StringBuffer();
   int i=0;
   while(!command.endsWith(";")){
     if(i++>0) message=i+"->";
  sb.append(" "+prompt(message));
  command = sb.toString().trim();
   }
   return command.substring(0,command.length()-1).trim();
 }
 public static void processSQL(Connection con,String sql){//数据库操作指令
   PreparedStatement ps = null;
   ResultSet rs = null;
   try{
     ps = con.prepareStatement(sql);
  int i = 0;
  if(ps.execute()){
    rs = ps.getResultSet();
    JdbcUtil.printRs(rs);
  }else{
    i = ps.getUpdateCount();
    System.out.println("更新成功-"+i);
  }
   }catch(Exception e){
     System.out.println("SQL执行错误-"+e.getMessage());
   }finally{
     JdbcUtil.close(rs,ps,null);
   }
 }
 public static String prompt(String message){//用户指令输入
   BufferedReader in =
    new BufferedReader(
      new InputStreamReader(System.in));
   String input = "";
   System.out.print(message);
   try{
     input = in.readLine();
   }catch(Exception e){
     System.out.println(e.getMessage());
   }
      return input;
 }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值