天天看点

100个Java经典例子(51-60)

[java]  view plain  copy

  1. package test51;  
  2. //文件名:ChatClient.java  
  3. import java.net.*;  
  4. import java.io.*;  
  5. public class ChatClient{  
  6.  private DatagramSocket s;  
  7.  private InetAddress hostAddress;  
  8.  private byte[] buf = new byte[1000];  
  9.  private DatagramPacket dp = new DatagramPacket(buf,buf.length);  
  10.   public ChatClient(){  
  11.    try{  
  12.        //使用构造器,创建使用本机任何可用端口的数据包Socket  
  13.        s = new DatagramSocket();  
  14.        //获取本地IP  
  15.        hostAddress = InetAddress.getByName("localhost");  
  16.        System.out.println("Client start............");  
  17.        while(true){  
  18.          String outMessage ="";    
  19.         //读取输入  
  20.          BufferedReader stdin  = new BufferedReader(new InputStreamReader(System.in));  
  21.          try{  
  22.            outMessage = stdin.readLine();  
  23.          }catch(IOException ie){  
  24.            System.err.println("IO error!");  
  25.          }  
  26.          //如果输入“bye”则表示退出程序  
  27.          if(outMessage.equals("bye")) break;  
  28.          String outString = "Client say: "+ outMessage;  
  29.          byte[] buf = outString.getBytes();  
  30.          //打包数据,发送数据  
  31.          DatagramPacket out = new DatagramPacket(buf,buf.length,hostAddress,ChatServer.PORT);  
  32.          s.send(out);  
  33.          //等待服务器返回  
  34.          s.receive(dp);  
  35.          String rcvd = "rcvd from "+ dp.getAddress() + ", " + dp.getPort() +   
  36.          ": "+ new String(dp.getData(),0,dp.getLength());  
  37.          System.out.println(rcvd);  
  38.       }  
  39.      }catch(UnknownHostException e){  
  40.        System.out.println("Can;t open socket");  
  41.        System.exit(1);  
  42.      }catch(SocketException e){  
  43.        System.out.println("Can;t open socket");  
  44.        e.printStackTrace();  
  45.        System.exit(1);  
  46.      }catch(IOException e){  
  47.        System.err.println("Communication error");  
  48.        e.printStackTrace();  
  49.        System.exit(1);  
  50.      }catch(Exception e){  
  51.        System.err.println("Communication error");  
  52.        e.printStackTrace();  
  53.        System.exit(1);  
  54.      }  
  55.      System.out.println("ChatClient over");  
  56.  }  
  57.  public static void main(String[] args){  
  58.     new ChatClient();  
  59.  }  
  60. }  

[java]  view plain  copy

  1. package test51;  
  2. import java.net.*;  
  3. import java.io.*;  
  4. import java.util.*;  
  5. public class ChatServer{  
  6.  static final int PORT = 4000;//设置服务端口  
  7.  private byte[] buf = new byte[1000];  
  8.  private DatagramPacket dgp =new  DatagramPacket(buf,buf.length);  
  9.  private DatagramSocket sk;  
  10.  public ChatServer(){  
  11.    try{  
  12.      //实例化数据报  
  13.      sk = new DatagramSocket(PORT);  
  14.      System.out.println("Server start.................");  
  15.      while(true){  
  16.        //等待接收  
  17.        sk.receive(dgp);  
  18.        //获取接收信息  
  19.        String rcvd = new String(dgp.getData(),0,dgp.getLength())+   
  20.           ", from address: "+ dgp.getAddress()+  
  21.           ", port: "+ dgp.getPort();  
  22.        System.out.println(rcvd);  
  23.        String outMessage ="";    
  24.         //读取输入  
  25.          BufferedReader stdin  = new BufferedReader(new InputStreamReader(System.in));  
  26.          try{  
  27.            outMessage = stdin.readLine();  
  28.          }catch(IOException ie){  
  29.            System.err.println("IO error!");  
  30.          }  
  31.        String outString = "Server say: "+ outMessage;  
  32.        //拷贝字符到缓存  
  33.        byte[] buf = outString.getBytes();  
  34.        //打包数据,发送回信息。  
  35.        DatagramPacket out = new DatagramPacket(buf,buf.length,dgp.getAddress(),dgp.getPort());  
  36.        sk.send(out);  
  37.      }  
  38.     }catch(SocketException e){  
  39.       System.err.println("Can't open socket");  
  40.       System.exit(1);  
  41.     }catch(IOException e){  
  42.      System.err.println("Communication error");  
  43.      e.printStackTrace();  
  44.      System.exit(1);  
  45.     }  
  46.  }  
  47.  public static void main(String[] args){  
  48.    new ChatServer();  
  49.  }  
  50. }  

[java]  view plain  copy

  1. package test52;  
  2. import java.sql.*;  
  3. public class odbcConn{  
  4.   private String url="";  
  5.   private String username="";  
  6.   private String password="";  
  7.   public Connection conn(){  
  8.      try {  
  9.         Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");  
  10.         Connection con = DriverManager.getConnection(url, username, password);  
  11.         return con;  
  12.     }catch(SQLException sqle){  
  13.         System.out.println("can't connection db:"+sqle);  
  14.         return null;  
  15.     } catch (Exception e) {  
  16.         System.out.println("Failed to load JDBC/ODBC driver.");  
  17.         return null;  
  18.      }  
  19.   }  
  20.   public void query(Connection con, String sql){  
  21.     try{  
  22.      if(con==null) return;  
  23.      Statement stmt = con.createStatement();  
  24.      ResultSet rs = stmt.executeQuery(sql);   
  25.      ResultSetMetaData rmeta = rs.getMetaData();  
  26.      int numColumns = rmeta.getColumnCount();  
  27.      while(rs.next())  
  28.      {  
  29.        for(int i = 0;i< numColumns;i++)  
  30.        {  
  31.         String sTemp = rs.getString(i+1);  
  32.         System.out.print(sTemp+"  ");  
  33.        }  
  34.       System.out.println("");     
  35.      }  
  36.     }catch(Exception e){  
  37.       System.out.println("query error:"+e);  
  38.     }finally{  
  39.        try{  
  40.        con.close();  
  41.       }catch(SQLException se){}  
  42.     }  
  43.   }  
  44.    public void execute(Connection con, String sql){  
  45.     try{  
  46.      if(con==null) return;  
  47.      Statement stmt = con.createStatement();  
  48.     stmt.executeUpdate(sql);   
  49.    }catch(Exception e){  
  50.       System.out.println("query error:"+e);  
  51.     }finally{  
  52.       try{  
  53.        con.close();  
  54.       }catch(SQLException se){}  
  55.     }  
  56.   }  
  57.   public static void main(String[] arg){  
  58.     if(arg.length!=3){  
  59.       System.out.println("use: java odbcConn url username password");  
  60.       return;  
  61.     }  
  62.     odbcConn oc = new odbcConn();  
  63.     oc.url = arg[0];  
  64.     oc.username=arg[1];  
  65.     oc.password=arg[2];  
  66.     oc.execute(oc.conn(),"insert into userinfo(name,address)values('switch','new York')");  
  67.     oc.query(oc.conn(),"select * from userinfo");  
  68.   }  
  69. }   

[java]  view plain  copy

  1. package test53;  
  2. import java.sql.*;  
  3. public class JDBCConn{  
  4.   private String url="";  
  5.   private  String username="";  
  6.   private  String password="";  
  7.   public Connection conn(){  
  8.      try {  
  9.         //加载JDBC驱动  
  10.         Class.forName("oracle.jdbc.driver.OracleDriver");  
  11.         //创建数据库连接  
  12.         Connection con = DriverManager.getConnection("jdbc:oracle:thin:@127.0.0.1:1521:ORCL", "test", "test");  
  13.         return con;  
  14.     }catch(ClassNotFoundException cnf){  
  15.         System.out.println("driver not find:"+cnf);  
  16.         return null;  
  17.     }catch(SQLException sqle){  
  18.         System.out.println("can't connection db:"+sqle);  
  19.         return null;  
  20.     } catch (Exception e) {  
  21.         System.out.println("Failed to load JDBC/ODBC driver.");  
  22.         return null;  
  23.      }  
  24.   }  
  25.   public void query(Connection con, String sql){  
  26.     try{  
  27.      if(con==null){  
  28.        throw new Exception("database connection can't use!");  
  29.      }  
  30.      if(sql==null) throw new Exception("check your parameter: 'sql'! don't input null!");  
  31.      //声明语句  
  32.      Statement stmt = con.createStatement();  
  33.      //执行查询  
  34.      ResultSet rs = stmt.executeQuery(sql);   
  35.      ResultSetMetaData rmeta = rs.getMetaData();  
  36.      //获得数据字段个数  
  37.      int numColumns = rmeta.getColumnCount();  
  38.      while(rs.next())  
  39.      {  
  40.        for(int i = 0;i< numColumns;i++)  
  41.        {  
  42.         String sTemp = rs.getString(i+1);  
  43.         System.out.print(sTemp+"  ");  
  44.        }  
  45.       System.out.println("");     
  46.      }  
  47.     }catch(Exception e){  
  48.       System.out.println("query error:"+e);  
  49.     }  
  50.   }  
  51.    public void execute(Connection con, String sql){  
  52.     try{  
  53.      if(con==null) return;  
  54.      Statement stmt = con.createStatement();  
  55.     stmt.executeUpdate(sql);   
  56.    }catch(Exception e){  
  57.       System.out.println("execute error: sql = "+sql);  
  58.       System.out.println(e);  
  59.     }  
  60.   }  
  61.   public void demo(){  
  62.     try{  
  63.       JDBCConn oc = new JDBCConn();  
  64.       Connection conn = oc.conn();  
  65.       String sql = "insert into TBL_USER(id,name,password)values(seq_user.nextval,'switch','haorenpingan')";  
  66.       oc.execute(conn,sql);  
  67.       sql = "select * from TBL_USER";  
  68.       oc.query(conn,sql);  
  69.       conn.close();  
  70.     }catch(SQLException se){  
  71.       System.out.println(se);  
  72.     }catch(Exception e){  
  73.       System.out.println(e);  
  74.     }  
  75.   }  
  76.   public static void main(String[] arg){  
  77.     if(arg.length!=3){  
  78.       System.out.println("use: java JDBCConn url username password");  
  79.       return;  
  80.     }  
  81.     JDBCConn oc = new JDBCConn();  
  82.     oc.url = arg[0];  
  83.     oc.username=arg[1];  
  84.     oc.password=arg[2];  
  85.     oc.demo();  
  86.   }  
  87. }   

[java]  view plain  copy

  1. package test54;  
  2. import java.sql.*;  
  3. import java.util.*;  
  4. public class StatementConn{  
  5.   private static String url="";  
  6.   private static String username="";  
  7.   private static String password="";  
  8.   Connection con = null;  
  9.   PreparedStatement updStmt=null;//语句对象  
  10.   public Connection conn(){  
  11.      try {  
  12.         //加载JDBC驱动  
  13.         Class.forName("oracle.jdbc.driver.OracleDriver");  
  14.         //创建数据库连接  
  15.         con = DriverManager.getConnection(url, username, password);  
  16.         return con;  
  17.     }catch(ClassNotFoundException cnf){  
  18.         System.out.println("driver not find:"+cnf);  
  19.         return null;  
  20.     }catch(SQLException sqle){  
  21.         System.out.println("can't connection db:"+sqle);  
  22.         return null;  
  23.     } catch (Exception e) {  
  24.         System.out.println("Failed to load JDBC/ODBC driver.");  
  25.         return null;  
  26.      }  
  27.   }  
  28.   public void close()   
  29.   {  
  30.     try  
  31.     {  
  32.      con.close();  
  33.     }  
  34.     catch(Throwable e){  
  35.       System.out.println(e);  
  36.     }  
  37.     con = null;  
  38.   }  
  39.   private PreparedStatement getStatement(String sql,Vector vCondition) throws SQLException{  
  40.     try  
  41.     {  
  42.       int i=0;  
  43.       Object temp;  
  44.       updStmt=conn().prepareStatement(sql);  
  45.        for (i=0;i<vCondition.size();i++){  
  46.         temp=vCondition.elementAt(i);  
  47.         if (temp instanceof Integer) {  
  48.           updStmt.setInt(i+1,((Integer)temp).intValue());  
  49.         }  
  50.         else if (temp instanceof Double) {  
  51.           updStmt.setDouble(i+1,((Double)temp).doubleValue());  
  52.         }  
  53.         else if (temp instanceof String) {  
  54.           String str=(temp.toString()).trim();  
  55.           updStmt.setString(i+1,str);  
  56.         }  
  57.         else {  
  58.             updStmt.setObject(i+1,temp);  
  59.         }  
  60.       }  
  61.     }  
  62.     catch(SQLException e)  
  63.     {  
  64.         throw e;  
  65.     }  
  66.     return updStmt;  
  67.   }  
  68.   private void closeUpdStmt()  
  69.   {  
  70.     try  
  71.     {  
  72.       if(updStmt!=null)  
  73.         updStmt.close();  
  74.     }  
  75.     catch(Throwable e)  
  76.     {  
  77.       System.out.println(e);  
  78.     }  
  79.     updStmt=null;  
  80.   }   
  81.   public Object execute(String sql,Vector vCondition) throws SQLException,Exception {  
  82.     java.sql.ResultSet rs = null;  
  83.     java.util.Vector vResult = null;  
  84.     try  
  85.     {  
  86.      if(!isSelect(sql))  
  87.      {  
  88.       //insert,update,delete  
  89.       try  
  90.       {  
  91.         Integer iResult=new Integer(getStatement(sql,vCondition).executeUpdate());  
  92.         return iResult;  
  93.       }  
  94.       catch(SQLException e1)  
  95.       {  
  96.          throw e1;  
  97.       }  
  98.     }  
  99.     else {  
  100.       //select  
  101.       rs = getStatement(sql,vCondition).executeQuery();  
  102.       int columnCount = rs.getMetaData().getColumnCount();  
  103.       vResult = new Vector();  
  104.       while(rs.next())  
  105.       {  
  106.        Vector vTemp = new Vector();  
  107.        for(int i = 0;i< columnCount;i++)  
  108.        {  
  109.         String sTemp = rs.getString(i+1);  
  110.         vTemp.addElement(sTemp== null ? "" : sTemp.trim());  
  111.        }  
  112.        vResult.addElement(vTemp);  
  113.       }  
  114.       rs.close();  
  115.       closeUpdStmt();  
  116.      }  
  117.     }  
  118.     catch(Exception e1)  
  119.     {  
  120.        throw e1;  
  121.     }  
  122.     finally  
  123.     {  
  124.       close();  
  125.     }  
  126.     return vResult;  
  127.   }  
  128.   protected boolean isSelect(String psql) {  
  129.     String sql = psql.trim().toUpperCase();  
  130.     if(sql.indexOf("SELECT") != 0) return false;  
  131.     return true;  
  132.   }  
  133.  public static void main(String[] arg){  
  134.     if(arg.length!=3){  
  135.       System.out.println("use: java StatementConn url username password");  
  136.       return;  
  137.     }  
  138.     url = arg[0];  
  139.     username=arg[1];  
  140.     password=arg[2];  
  141.     demo();  
  142.   }  
  143.   public static void demo(){  
  144.     try{  
  145.       StatementConn oc = new StatementConn();  
  146.       String sql = "select * from TBL_USER where id>?";  
  147.       Vector vCondition =new Vector();  
  148.       vCondition.addElement(new Integer(3));  
  149.       Vector vResult = (Vector)oc.execute(sql,vCondition);  
  150.       for(int i=0;i<vResult.size();i++){  
  151.        System.out.println(vResult.elementAt(i));  
  152.       }  
  153.     }catch(Exception e){  
  154.       System.out.println(e);  
  155.     }  
  156.   }  
  157. }//end  

[java]  view plain  copy

  1. package test56;  
  2. import java.sql.*;  
  3. public class JDBCDataMeta {  
  4.  private String url="";  
  5.  private String username="";  
  6.  private String password="";  
  7.  public static void main(java.lang.String[] args) {  
  8.     if(args.length!=4){  
  9.       System.out.println("use: java JDBCDataMeta url username password tablename");  
  10.       return;  
  11.     }  
  12.     JDBCDataMeta JDM = new JDBCDataMeta();  
  13.     JDM.url = args[0];  
  14.     JDM.username=args[1];  
  15.     JDM.password=args[2];  
  16.     JDM.getMeta(JDM.conn(),args[3]);  
  17. }  
  18.   public Connection conn(){  
  19.      try {  
  20.         Class.forName("oracle.jdbc.driver.OracleDriver");  
  21.         Connection con = DriverManager.getConnection(url, username, password);  
  22.         return con;  
  23.     }catch(ClassNotFoundException cf){  
  24.         System.out.println("can't find class"+cf);  
  25.         return null;  
  26.     }catch(SQLException sqle){  
  27.         System.out.println("can't connection db:"+sqle);  
  28.         return null;  
  29.     } catch (Exception e) {  
  30.         System.out.println("Failed to load JDBC/ODBC driver.");  
  31.         return null;  
  32.     }  
  33.   }  
  34.   public void getMeta(Connection con, String table){  
  35.    try {  
  36.      DatabaseMetaData dbmd = con.getMetaData();  
  37.      //获取驱动名  
  38.      String dataName = dbmd.getDriverName();  
  39.      String dataURL = dbmd.getURL();  
  40.      System.out.println("**************** DATA META Comment  *********************");  
  41.      System.out.println("dataName="+dataName);  
  42.      System.out.println("dataURL="+dataURL);  
  43.      //获取数据库最大支持字节数  
  44.      int dataMaxSize = dbmd.getMaxRowSize();  
  45.      System.out.println("dataMaxSize="+dataMaxSize);  
  46.      //获取数据库表信息  
  47.      String[] types = new String[1];  
  48.      types[0] = "TABLE";   
  49.      ResultSet results = dbmd.getTables(null, null, "%", types);  
  50.      System.out.println("********************tables information********************");  
  51.      while (results.next())   
  52.      {  
  53.         System.err.println("----------------------------");  
  54.         System.err.println("TABLE_CAT   : "+results.getObject(1));  
  55.         System.err.println("TABLE_SCHEM : "+results.getObject(2));  
  56.         System.err.println("TABLE_NAME  : "+results.getObject(3));  
  57.         System.err.println("TABLE_TYPE  : "+results.getObject(4));  
  58.         System.err.println("REMARKS     : "+results.getObject(5));  
  59.     }  
  60.      //获取表主键信息  
  61.      ResultSet pkRSet = dbmd.getPrimaryKeys(null, null, table);  
  62.      System.out.println("********************PK information********************");  
  63.       while(pkRSet.next()){  
  64.         System.err.println("TABLE_CAT : "+pkRSet.getObject(1));  
  65.         System.err.println("TABLE_SCHEM: "+pkRSet.getObject(2));  
  66.         System.err.println("TABLE_NAME : "+pkRSet.getObject(3));  
  67.         System.err.println("COLUMN_NAME: "+pkRSet.getObject(4));  
  68.         System.err.println("KEY_SEQ : "+pkRSet.getObject(5));  
  69.         System.err.println("PK_NAME : "+pkRSet.getObject(6));  
  70.      }  
  71.     System.out.println("*****************FK information***********************");  
  72.     //获取表外键信息  
  73.     results = dbmd.getImportedKeys(null, null, table);  
  74.      while (results.next())   
  75.      {  
  76.         System.err.println("PKTABLE_CAT   : "+results.getObject(1));  
  77.         System.err.println("PKTABLE_SCHEM : "+results.getObject(2));  
  78.         System.err.println("PKTABLE_NAME  : "+results.getObject(3));  
  79.         System.err.println("PKCOLUMN_NAME : "+results.getObject(4));  
  80.         System.err.println("FKTABLE_CAT   : "+results.getObject(5));  
  81.         System.err.println("FKTABLE_SCHEM : "+results.getObject(6));  
  82.         System.err.println("FKTABLE_NAME  : "+results.getObject(7));  
  83.         System.err.println("FKCOLUMN_NAME : "+results.getObject(8));  
  84.         System.err.println("KEY_SEQ       : "+results.getObject(9));  
  85.         System.err.println("UPDATE_RULE   : "+results.getObject(10));  
  86.         System.err.println("DELETE_RULE   : "+results.getObject(11));  
  87.         System.err.println("FK_NAME       : "+results.getObject(12));  
  88.         System.err.println("PK_NAME       : "+results.getObject(13));  
  89.         System.err.println("DEFERRABILITY : "+results.getObject(13));  
  90.     }  
  91.      }catch (SQLException se) {  
  92.        // 输出数据库连接错误信息  
  93.        System.out.println("SQL Exception: " + se.getMessage());  
  94.        se.printStackTrace(System.out);  
  95.     }catch(Exception e){  
  96.        System.out.println(e);  
  97.     }finally{  
  98.        try{  
  99.        con.close();  
  100.       }catch(SQLException se){}  
  101.     }   
  102.   }  
  103. }  

[java]  view plain  copy

  1. package test57;  
  2. import java.sql.*;  
  3. public class JDBCResultMeta {  
  4.  private String url="";  
  5.  private String username="";  
  6.  private String password="";  
  7.  public static void main(java.lang.String[] args) {  
  8.     if(args.length!=4){  
  9.       System.out.println("use: java JDBCResultMeta url username password tablename");  
  10.       return;  
  11.     }  
  12.     JDBCResultMeta JRM = new JDBCResultMeta();  
  13.     JRM.url = args[0];  
  14.     JRM.username=args[1];  
  15.     JRM.password=args[2];  
  16.     JRM.getMeta(JRM.conn(),args[3]);  
  17. }  
  18.   public Connection conn(){  
  19.      try {  
  20.         Class.forName("oracle.jdbc.driver.OracleDriver");  
  21.         Connection con = DriverManager.getConnection(url, username, password);  
  22.         return con;  
  23.     }catch(ClassNotFoundException cf){  
  24.         System.out.println("can't find class"+cf);  
  25.         return null;  
  26.     }catch(SQLException sqle){  
  27.         System.out.println("can't connection db:"+sqle);  
  28.         return null;  
  29.     } catch (Exception e) {  
  30.         System.out.println("Failed to load JDBC/ODBC driver.");  
  31.         return null;  
  32.     }  
  33.   }  
  34.   public void getMeta(Connection con, String table){  
  35.    try {  
  36.      Statement Stm = con.createStatement();  
  37.      String sql="select * from "+table;  
  38.      ResultSet rs = Stm.executeQuery(sql);  
  39.      ResultSetMetaData lineInfo = rs.getMetaData();  
  40.      System.out.println("*********************RESULT META Comment************************");  
  41.      //获取数据列数  
  42.      int columnCount = lineInfo.getColumnCount();  
  43.      System.out.println("Column Count :"+columnCount);  
  44.      //获取数据列类型  
  45.      for(int i=1;i<columnCount+1;i++){  
  46.        String columeName = lineInfo.getColumnName(i);  
  47.        String columeType = lineInfo.getColumnTypeName(i);  
  48.        boolean autocol = lineInfo.isAutoIncrement(i);  
  49.        System.out.println(columeName+" = "+columeType +"  :::  "+autocol);  
  50.      }  
  51.      }catch (SQLException se) {  
  52.        // 输出数据库连接错误信息  
  53.        System.out.println("SQL Exception: " + se.getMessage());  
  54.        se.printStackTrace(System.out);  
  55.     }catch(Exception e){  
  56.        System.out.println(e);  
  57.     }finally{  
  58.        try{  
  59.        con.close();  
  60.       }catch(SQLException se){}  
  61.     }   
  62.   }  
  63. }  

[java]  view plain  copy

  1. package test58;  
  2. import java.sql.*;  
  3. public class JDBCSTMConn{  
  4.   private static String url="";  
  5.   private static String username="";  
  6.   private static String password="";  
  7.   public Connection conn(){  
  8.      try {  
  9.         //加载JDBC驱动  
  10.         Class.forName("oracle.jdbc.driver.OracleDriver");  
  11.         //创建数据库连接  
  12.         Connection con = DriverManager.getConnection(url, username, password);  
  13.         return con;  
  14.     }catch(ClassNotFoundException cnf){  
  15.         System.out.println("driver not find:"+cnf);  
  16.         return null;  
  17.     }catch(SQLException sqle){  
  18.         System.out.println("can't connection db:"+sqle);  
  19.         return null;  
  20.     } catch (Exception e) {  
  21.         System.out.println("Failed to load JDBC/ODBC driver.");  
  22.         return null;  
  23.      }  
  24.   }  
  25.    public void execute(Connection con){  
  26.     CallableStatement toesUp = null;   
  27.     try {   
  28.       con.setAutoCommit(false);   
  29.       //调用存储过程  
  30.       toesUp = con.prepareCall("{call p_test(?)}");   
  31.       //传递参数给存储过程  
  32.       toesUp.setInt(1, 6);  
  33.       //执行存储过程  
  34.       toesUp.executeQuery();  
  35.       Statement stmt = con.createStatement();  
  36.       ResultSet rs = (ResultSet) stmt.executeQuery("SELECT * FROM TEST");   
  37.       while (rs.next()) {   
  38.         String ID = rs.getString(1);   
  39.         String NAME = rs.getString(2);   
  40.         System.out.println(ID+ " " +NAME);  
  41.       }   
  42.       rs.close();   
  43.     } catch (SQLException e) {   
  44.     System.out.println(e);  
  45.     try{  
  46.     toesUp.close();   
  47.     con.close();  
  48.     }catch(Exception es){System.out.println(es);}   
  49.    }  
  50.   }  
  51.   public void demo(){  
  52.     try{  
  53.       JDBCSTMConn oc = new JDBCSTMConn();  
  54.       Connection conn = oc.conn();  
  55.       oc.execute(conn);  
  56.       conn.close();  
  57.     }catch(SQLException se){  
  58.       System.out.println(se);  
  59.     }catch(Exception e){  
  60.       System.out.println(e);  
  61.     }  
  62.   }  
  63.   public static void main(String[] arg){  
  64.     if(arg.length!=3){  
  65.       System.out.println("use: java JDBCSTMConn url username password");  
  66.       return;  
  67.     }  
  68.     JDBCSTMConn oc = new JDBCSTMConn();  
  69.     oc.url = arg[0];  
  70.     oc.username=arg[1];  
  71.     oc.password=arg[2];  
  72.     oc.demo();  
  73.   }  
  74. }   

[java]  view plain  copy

  1. package test59;  
  2. import java.sql.*;  
  3. public class JDBCConnCommit{  
  4.   private static String url="";  
  5.   private static String username="";  
  6.   private static String password="";  
  7.   public Connection conn(){  
  8.      try {  
  9.         //加载JDBC驱动  
  10.         Class.forName("oracle.jdbc.driver.OracleDriver");  
  11.         //创建数据库连接  
  12.         Connection con = DriverManager.getConnection(url, username, password);  
  13.         return con;  
  14.     }catch(ClassNotFoundException cnf){  
  15.         System.out.println("driver not find:"+cnf);  
  16.         return null;  
  17.     }catch(SQLException sqle){  
  18.         System.out.println("can't connection db:"+sqle);  
  19.         return null;  
  20.     } catch (Exception e) {  
  21.         System.out.println("Failed to load JDBC/ODBC driver.");  
  22.         return null;  
  23.      }  
  24.   }  
  25.   public void query(Connection con, String sql) throws SQLException,Exception {  
  26.     try{  
  27.      if(con==null){  
  28.        throw new Exception("database connection can't use!");  
  29.      }  
  30.      if(sql==null) throw new Exception("check your parameter: 'sql'! don't input null!");  
  31.      //声明语句  
  32.      Statement stmt = con.createStatement();  
  33.      //执行查询  
  34.      ResultSet rs = stmt.executeQuery(sql);   
  35.      ResultSetMetaData rmeta = rs.getMetaData();  
  36.      //获得数据字段个数  
  37.      int numColumns = rmeta.getColumnCount();  
  38.      while(rs.next())  
  39.      {  
  40.        for(int i = 0;i< numColumns;i++)  
  41.        {  
  42.         String sTemp = rs.getString(i+1);  
  43.         System.out.print(sTemp+"  ");  
  44.        }  
  45.       System.out.println("");     
  46.      }  
  47.      rs.close();  
  48.      stmt.close();  
  49.     }catch(Exception e){  
  50.       System.out.println("query error: sql = "+sql);  
  51.       System.out.println("query error:"+e);  
  52.       throw new SQLException("query error");  
  53.     }  
  54.   }  
  55.    public void execute(Connection con, String sql) throws SQLException  {  
  56.     try{  
  57.      if(con==null) return;  
  58.      Statement stmt = con.createStatement();  
  59.      int i = stmt.executeUpdate(sql);   
  60.      System.out.println("update row:"+i);  
  61.      stmt.close();  
  62.    }catch(Exception e){  
  63.       System.out.println("execute error: sql = "+sql);  
  64.       System.out.println(e);  
  65.       throw new SQLException("execute error");  
  66.     }  
  67.   }  
  68.   public void demo(){  
  69.       JDBCConnCommit oc = new JDBCConnCommit();  
  70.       Connection conn = oc.conn();  
  71.     try{  
  72.       conn.setAutoCommit( false );  
  73.       String sql = "";  
  74.       for(int i=0;i<4;i++){  
  75.       sql = "insert into TBL_USER(id,name,password)values(seq_user.nextval,'tom','haorenpingan')";  
  76.       oc.execute(conn,sql);  
  77.       }  
  78.       sql = "select * from TBL_USER where name='tom' order by id";  
  79.       oc.query(conn,sql);  
  80.       sql = "delete from TBL_USER where name='tom'";  
  81.       oc.execute(conn,sql);  
  82.       conn.commit();  
  83.     }catch(SQLException se){  
  84.       try{  
  85.         conn.rollback();   
  86.       }catch(Exception e){  
  87.       }  
  88.       System.out.println(se);  
  89.     }catch(Exception e){   
  90.       System.out.println(e);  
  91.     }finally  
  92.     {   
  93.       try{  
  94.        conn.close();  
  95.      }catch(SQLException e){}  
  96.     }  
  97.   }  
  98.   public static void main(String[] arg){  
  99.     if(arg.length!=3){  
  100.       System.out.println("use: java JDBCConnCommit url username password");  
  101.       return;  
  102.     }  
  103.     JDBCConnCommit oc = new JDBCConnCommit();  
  104.     oc.url = arg[0];  
  105.     oc.username=arg[1];  
  106.     oc.password=arg[2];  
  107.     oc.demo();  
  108.   }  
  109. }   

[java]  view plain  copy

  1. package test60;  
  2. public class oneThread extends Thread {  
  3. public oneThread() {  
  4.  }  
  5.  public void run() {  
  6.   System.out.println("...............oneThread begining................");  
  7.   int flag = 0;  
  8.   while(true) {  
  9.     if(flag==20){  
  10.       System.out.println("\n...............oneThread end............. ");  
  11.       break;  
  12.     }  
  13.      for(int i=0;i<flag;i++)  
  14.        System.out.print("*");  
  15.      System.out.println("");  
  16.      flag++;  
  17.    try{  
  18.      //睡眠0.1秒  
  19.      sleep(100);  
  20.    }catch(Exception e){  
  21.    }     
  22.   }  
  23.  }  
  24.  public static void main(String args[]) {  
  25.     new oneThread().start();  
  26.  }  
  27. }  

继续阅读