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