浏览 1780 次
锁定老帖子 主题:仿SQLPLUS
精华帖 (0) :: 良好帖 (0) :: 新手帖 (0) :: 隐藏帖 (0)
|
|
---|---|
作者 | 正文 |
发表时间:2009-08-27
import java.sql.*; import java.io.*; public class SQLTools{ public static void main(String[] args){ StringBuffer info=new StringBuffer(); info.append("-------read me--------\n"); info.append("commit;---excute con.commit();---\n"); info.append("rollback;---excute con.rollback();---\n"); info.append("sqlString;---excute sql command;---\n"); info.append("quit;---excute con.commit() and quit program---\n"); info.append("-----------end-----------\n"); System.out.println(info.toString()); Connection con= null; while((con=getConnection())==null){} try{ con.setAutoCommit(false); StringBuffer sb=new StringBuffer(); String cmd=""; boolean flag=true; int c=0; String message=""; while(flag){ if(c++==0){ message="SQLTools-> "; }else{ message=c+"-> "; } sb.append(prompt(message)); cmd=sb.toString().trim(); if(cmd.endsWith(";")){ String sql=cmd.substring(0,cmd.length()-1); if("quit".equals(sql)){ flag=false; con.commit(); sb=new StringBuffer(); c=0; }else if("commit".equals(sql)){ con.commit(); sb=new StringBuffer(); c=0; }else if("rollback".equals(sql)){ con.rollback(); sb=new StringBuffer(); c=0; }else{ System.out.println(sql); execute(sql,con); sb=new StringBuffer(); c=0; } } } }catch(Exception e){System.out.println("rollback"); try{if(con!=null)con.rollback(); }catch(Exception e3){e3.printStackTrace();} } finally{JdbcUtil.release(con);} } public static Connection getConnection(){ String message="url:\n"; String url=prompt(message); message="username:\n"; String username=prompt(message); message="password:\n"; String pwd=prompt(message); Connection con=null; try{ con=DriverManager.getConnection(url,username,pwd); }catch(Exception e){System.out.println("->connection failed");} return con; } public static String prompt(String message){ BufferedReader in=new BufferedReader(new InputStreamReader(System.in)); System.out.println(message); String input=""; try{ input=in.readLine(); }catch(Exception e){e.printStackTrace();} return input; } public static void execute(String sql,Connection con)throws Exception{ int c=0; Statement stmt=null; ResultSet rs=null; try{ stmt=con.createStatement(); if(stmt.execute(sql)){ rs=stmt.getResultSet(); JdbcUtil.printRs(rs); }else{ c=stmt.getUpdateCount(); System.out.println("update succefully!"+c); } }catch(Exception e){System.out.println("database manipulation failed!");} finally{JdbcUtil.release(rs,stmt,null);} } } 声明:ITeye文章版权属于作者,受法律保护。没有作者书面许可不得转载。
推荐链接
|
|
返回顶楼 | |