[java] view plain copy
- package test51;
- //文件名:ChatClient.java
- import java.net.*;
- import java.io.*;
- public class ChatClient{
- private DatagramSocket s;
- private InetAddress hostAddress;
- private byte[] buf = new byte[1000];
- private DatagramPacket dp = new DatagramPacket(buf,buf.length);
- public ChatClient(){
- try{
- //使用构造器,创建使用本机任何可用端口的数据包Socket
- s = new DatagramSocket();
- //获取本地IP
- hostAddress = InetAddress.getByName("localhost");
- System.out.println("Client start............");
- while(true){
- String outMessage ="";
- //读取输入
- BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in));
- try{
- outMessage = stdin.readLine();
- }catch(IOException ie){
- System.err.println("IO error!");
- }
- //如果输入“bye”则表示退出程序
- if(outMessage.equals("bye")) break;
- String outString = "Client say: "+ outMessage;
- byte[] buf = outString.getBytes();
- //打包数据,发送数据
- DatagramPacket out = new DatagramPacket(buf,buf.length,hostAddress,ChatServer.PORT);
- s.send(out);
- //等待服务器返回
- s.receive(dp);
- String rcvd = "rcvd from "+ dp.getAddress() + ", " + dp.getPort() +
- ": "+ new String(dp.getData(),0,dp.getLength());
- System.out.println(rcvd);
- }
- }catch(UnknownHostException e){
- System.out.println("Can;t open socket");
- System.exit(1);
- }catch(SocketException e){
- System.out.println("Can;t open socket");
- e.printStackTrace();
- System.exit(1);
- }catch(IOException e){
- System.err.println("Communication error");
- e.printStackTrace();
- System.exit(1);
- }catch(Exception e){
- System.err.println("Communication error");
- e.printStackTrace();
- System.exit(1);
- }
- System.out.println("ChatClient over");
- }
- public static void main(String[] args){
- new ChatClient();
- }
- }
[java] view plain copy
- package test51;
- import java.net.*;
- import java.io.*;
- import java.util.*;
- public class ChatServer{
- static final int PORT = 4000;//设置服务端口
- private byte[] buf = new byte[1000];
- private DatagramPacket dgp =new DatagramPacket(buf,buf.length);
- private DatagramSocket sk;
- public ChatServer(){
- try{
- //实例化数据报
- sk = new DatagramSocket(PORT);
- System.out.println("Server start.................");
- while(true){
- //等待接收
- sk.receive(dgp);
- //获取接收信息
- String rcvd = new String(dgp.getData(),0,dgp.getLength())+
- ", from address: "+ dgp.getAddress()+
- ", port: "+ dgp.getPort();
- System.out.println(rcvd);
- String outMessage ="";
- //读取输入
- BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in));
- try{
- outMessage = stdin.readLine();
- }catch(IOException ie){
- System.err.println("IO error!");
- }
- String outString = "Server say: "+ outMessage;
- //拷贝字符到缓存
- byte[] buf = outString.getBytes();
- //打包数据,发送回信息。
- DatagramPacket out = new DatagramPacket(buf,buf.length,dgp.getAddress(),dgp.getPort());
- sk.send(out);
- }
- }catch(SocketException e){
- System.err.println("Can't open socket");
- System.exit(1);
- }catch(IOException e){
- System.err.println("Communication error");
- e.printStackTrace();
- System.exit(1);
- }
- }
- public static void main(String[] args){
- new ChatServer();
- }
- }
[java] view plain copy
- package test52;
- import java.sql.*;
- public class odbcConn{
- private String url="";
- private String username="";
- private String password="";
- public Connection conn(){
- try {
- Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
- Connection con = DriverManager.getConnection(url, username, password);
- return con;
- }catch(SQLException sqle){
- System.out.println("can't connection db:"+sqle);
- return null;
- } catch (Exception e) {
- System.out.println("Failed to load JDBC/ODBC driver.");
- return null;
- }
- }
- public void query(Connection con, String sql){
- try{
- if(con==null) return;
- Statement stmt = con.createStatement();
- ResultSet rs = stmt.executeQuery(sql);
- ResultSetMetaData rmeta = rs.getMetaData();
- int numColumns = rmeta.getColumnCount();
- while(rs.next())
- {
- for(int i = 0;i< numColumns;i++)
- {
- String sTemp = rs.getString(i+1);
- System.out.print(sTemp+" ");
- }
- System.out.println("");
- }
- }catch(Exception e){
- System.out.println("query error:"+e);
- }finally{
- try{
- con.close();
- }catch(SQLException se){}
- }
- }
- public void execute(Connection con, String sql){
- try{
- if(con==null) return;
- Statement stmt = con.createStatement();
- stmt.executeUpdate(sql);
- }catch(Exception e){
- System.out.println("query error:"+e);
- }finally{
- try{
- con.close();
- }catch(SQLException se){}
- }
- }
- public static void main(String[] arg){
- if(arg.length!=3){
- System.out.println("use: java odbcConn url username password");
- return;
- }
- odbcConn oc = new odbcConn();
- oc.url = arg[0];
- oc.username=arg[1];
- oc.password=arg[2];
- oc.execute(oc.conn(),"insert into userinfo(name,address)values('switch','new York')");
- oc.query(oc.conn(),"select * from userinfo");
- }
- }
[java] view plain copy
- package test53;
- import java.sql.*;
- public class JDBCConn{
- private String url="";
- private String username="";
- private String password="";
- public Connection conn(){
- try {
- //加载JDBC驱动
- Class.forName("oracle.jdbc.driver.OracleDriver");
- //创建数据库连接
- Connection con = DriverManager.getConnection("jdbc:oracle:thin:@127.0.0.1:1521:ORCL", "test", "test");
- return con;
- }catch(ClassNotFoundException cnf){
- System.out.println("driver not find:"+cnf);
- return null;
- }catch(SQLException sqle){
- System.out.println("can't connection db:"+sqle);
- return null;
- } catch (Exception e) {
- System.out.println("Failed to load JDBC/ODBC driver.");
- return null;
- }
- }
- public void query(Connection con, String sql){
- try{
- if(con==null){
- throw new Exception("database connection can't use!");
- }
- if(sql==null) throw new Exception("check your parameter: 'sql'! don't input null!");
- //声明语句
- Statement stmt = con.createStatement();
- //执行查询
- ResultSet rs = stmt.executeQuery(sql);
- ResultSetMetaData rmeta = rs.getMetaData();
- //获得数据字段个数
- int numColumns = rmeta.getColumnCount();
- while(rs.next())
- {
- for(int i = 0;i< numColumns;i++)
- {
- String sTemp = rs.getString(i+1);
- System.out.print(sTemp+" ");
- }
- System.out.println("");
- }
- }catch(Exception e){
- System.out.println("query error:"+e);
- }
- }
- public void execute(Connection con, String sql){
- try{
- if(con==null) return;
- Statement stmt = con.createStatement();
- stmt.executeUpdate(sql);
- }catch(Exception e){
- System.out.println("execute error: sql = "+sql);
- System.out.println(e);
- }
- }
- public void demo(){
- try{
- JDBCConn oc = new JDBCConn();
- Connection conn = oc.conn();
- String sql = "insert into TBL_USER(id,name,password)values(seq_user.nextval,'switch','haorenpingan')";
- oc.execute(conn,sql);
- sql = "select * from TBL_USER";
- oc.query(conn,sql);
- conn.close();
- }catch(SQLException se){
- System.out.println(se);
- }catch(Exception e){
- System.out.println(e);
- }
- }
- public static void main(String[] arg){
- if(arg.length!=3){
- System.out.println("use: java JDBCConn url username password");
- return;
- }
- JDBCConn oc = new JDBCConn();
- oc.url = arg[0];
- oc.username=arg[1];
- oc.password=arg[2];
- oc.demo();
- }
- }
[java] view plain copy
- package test54;
- import java.sql.*;
- import java.util.*;
- public class StatementConn{
- private static String url="";
- private static String username="";
- private static String password="";
- Connection con = null;
- PreparedStatement updStmt=null;//语句对象
- public Connection conn(){
- try {
- //加载JDBC驱动
- Class.forName("oracle.jdbc.driver.OracleDriver");
- //创建数据库连接
- con = DriverManager.getConnection(url, username, password);
- return con;
- }catch(ClassNotFoundException cnf){
- System.out.println("driver not find:"+cnf);
- return null;
- }catch(SQLException sqle){
- System.out.println("can't connection db:"+sqle);
- return null;
- } catch (Exception e) {
- System.out.println("Failed to load JDBC/ODBC driver.");
- return null;
- }
- }
- public void close()
- {
- try
- {
- con.close();
- }
- catch(Throwable e){
- System.out.println(e);
- }
- con = null;
- }
- private PreparedStatement getStatement(String sql,Vector vCondition) throws SQLException{
- try
- {
- int i=0;
- Object temp;
- updStmt=conn().prepareStatement(sql);
- for (i=0;i<vCondition.size();i++){
- temp=vCondition.elementAt(i);
- if (temp instanceof Integer) {
- updStmt.setInt(i+1,((Integer)temp).intValue());
- }
- else if (temp instanceof Double) {
- updStmt.setDouble(i+1,((Double)temp).doubleValue());
- }
- else if (temp instanceof String) {
- String str=(temp.toString()).trim();
- updStmt.setString(i+1,str);
- }
- else {
- updStmt.setObject(i+1,temp);
- }
- }
- }
- catch(SQLException e)
- {
- throw e;
- }
- return updStmt;
- }
- private void closeUpdStmt()
- {
- try
- {
- if(updStmt!=null)
- updStmt.close();
- }
- catch(Throwable e)
- {
- System.out.println(e);
- }
- updStmt=null;
- }
- public Object execute(String sql,Vector vCondition) throws SQLException,Exception {
- java.sql.ResultSet rs = null;
- java.util.Vector vResult = null;
- try
- {
- if(!isSelect(sql))
- {
- //insert,update,delete
- try
- {
- Integer iResult=new Integer(getStatement(sql,vCondition).executeUpdate());
- return iResult;
- }
- catch(SQLException e1)
- {
- throw e1;
- }
- }
- else {
- //select
- rs = getStatement(sql,vCondition).executeQuery();
- int columnCount = rs.getMetaData().getColumnCount();
- vResult = new Vector();
- while(rs.next())
- {
- Vector vTemp = new Vector();
- for(int i = 0;i< columnCount;i++)
- {
- String sTemp = rs.getString(i+1);
- vTemp.addElement(sTemp== null ? "" : sTemp.trim());
- }
- vResult.addElement(vTemp);
- }
- rs.close();
- closeUpdStmt();
- }
- }
- catch(Exception e1)
- {
- throw e1;
- }
- finally
- {
- close();
- }
- return vResult;
- }
- protected boolean isSelect(String psql) {
- String sql = psql.trim().toUpperCase();
- if(sql.indexOf("SELECT") != 0) return false;
- return true;
- }
- public static void main(String[] arg){
- if(arg.length!=3){
- System.out.println("use: java StatementConn url username password");
- return;
- }
- url = arg[0];
- username=arg[1];
- password=arg[2];
- demo();
- }
- public static void demo(){
- try{
- StatementConn oc = new StatementConn();
- String sql = "select * from TBL_USER where id>?";
- Vector vCondition =new Vector();
- vCondition.addElement(new Integer(3));
- Vector vResult = (Vector)oc.execute(sql,vCondition);
- for(int i=0;i<vResult.size();i++){
- System.out.println(vResult.elementAt(i));
- }
- }catch(Exception e){
- System.out.println(e);
- }
- }
- }//end
[java] view plain copy
- package test56;
- import java.sql.*;
- public class JDBCDataMeta {
- private String url="";
- private String username="";
- private String password="";
- public static void main(java.lang.String[] args) {
- if(args.length!=4){
- System.out.println("use: java JDBCDataMeta url username password tablename");
- return;
- }
- JDBCDataMeta JDM = new JDBCDataMeta();
- JDM.url = args[0];
- JDM.username=args[1];
- JDM.password=args[2];
- JDM.getMeta(JDM.conn(),args[3]);
- }
- public Connection conn(){
- try {
- Class.forName("oracle.jdbc.driver.OracleDriver");
- Connection con = DriverManager.getConnection(url, username, password);
- return con;
- }catch(ClassNotFoundException cf){
- System.out.println("can't find class"+cf);
- return null;
- }catch(SQLException sqle){
- System.out.println("can't connection db:"+sqle);
- return null;
- } catch (Exception e) {
- System.out.println("Failed to load JDBC/ODBC driver.");
- return null;
- }
- }
- public void getMeta(Connection con, String table){
- try {
- DatabaseMetaData dbmd = con.getMetaData();
- //获取驱动名
- String dataName = dbmd.getDriverName();
- String dataURL = dbmd.getURL();
- System.out.println("**************** DATA META Comment *********************");
- System.out.println("dataName="+dataName);
- System.out.println("dataURL="+dataURL);
- //获取数据库最大支持字节数
- int dataMaxSize = dbmd.getMaxRowSize();
- System.out.println("dataMaxSize="+dataMaxSize);
- //获取数据库表信息
- String[] types = new String[1];
- types[0] = "TABLE";
- ResultSet results = dbmd.getTables(null, null, "%", types);
- System.out.println("********************tables information********************");
- while (results.next())
- {
- System.err.println("----------------------------");
- System.err.println("TABLE_CAT : "+results.getObject(1));
- System.err.println("TABLE_SCHEM : "+results.getObject(2));
- System.err.println("TABLE_NAME : "+results.getObject(3));
- System.err.println("TABLE_TYPE : "+results.getObject(4));
- System.err.println("REMARKS : "+results.getObject(5));
- }
- //获取表主键信息
- ResultSet pkRSet = dbmd.getPrimaryKeys(null, null, table);
- System.out.println("********************PK information********************");
- while(pkRSet.next()){
- System.err.println("TABLE_CAT : "+pkRSet.getObject(1));
- System.err.println("TABLE_SCHEM: "+pkRSet.getObject(2));
- System.err.println("TABLE_NAME : "+pkRSet.getObject(3));
- System.err.println("COLUMN_NAME: "+pkRSet.getObject(4));
- System.err.println("KEY_SEQ : "+pkRSet.getObject(5));
- System.err.println("PK_NAME : "+pkRSet.getObject(6));
- }
- System.out.println("*****************FK information***********************");
- //获取表外键信息
- results = dbmd.getImportedKeys(null, null, table);
- while (results.next())
- {
- System.err.println("PKTABLE_CAT : "+results.getObject(1));
- System.err.println("PKTABLE_SCHEM : "+results.getObject(2));
- System.err.println("PKTABLE_NAME : "+results.getObject(3));
- System.err.println("PKCOLUMN_NAME : "+results.getObject(4));
- System.err.println("FKTABLE_CAT : "+results.getObject(5));
- System.err.println("FKTABLE_SCHEM : "+results.getObject(6));
- System.err.println("FKTABLE_NAME : "+results.getObject(7));
- System.err.println("FKCOLUMN_NAME : "+results.getObject(8));
- System.err.println("KEY_SEQ : "+results.getObject(9));
- System.err.println("UPDATE_RULE : "+results.getObject(10));
- System.err.println("DELETE_RULE : "+results.getObject(11));
- System.err.println("FK_NAME : "+results.getObject(12));
- System.err.println("PK_NAME : "+results.getObject(13));
- System.err.println("DEFERRABILITY : "+results.getObject(13));
- }
- }catch (SQLException se) {
- // 输出数据库连接错误信息
- System.out.println("SQL Exception: " + se.getMessage());
- se.printStackTrace(System.out);
- }catch(Exception e){
- System.out.println(e);
- }finally{
- try{
- con.close();
- }catch(SQLException se){}
- }
- }
- }
[java] view plain copy
- package test57;
- import java.sql.*;
- public class JDBCResultMeta {
- private String url="";
- private String username="";
- private String password="";
- public static void main(java.lang.String[] args) {
- if(args.length!=4){
- System.out.println("use: java JDBCResultMeta url username password tablename");
- return;
- }
- JDBCResultMeta JRM = new JDBCResultMeta();
- JRM.url = args[0];
- JRM.username=args[1];
- JRM.password=args[2];
- JRM.getMeta(JRM.conn(),args[3]);
- }
- public Connection conn(){
- try {
- Class.forName("oracle.jdbc.driver.OracleDriver");
- Connection con = DriverManager.getConnection(url, username, password);
- return con;
- }catch(ClassNotFoundException cf){
- System.out.println("can't find class"+cf);
- return null;
- }catch(SQLException sqle){
- System.out.println("can't connection db:"+sqle);
- return null;
- } catch (Exception e) {
- System.out.println("Failed to load JDBC/ODBC driver.");
- return null;
- }
- }
- public void getMeta(Connection con, String table){
- try {
- Statement Stm = con.createStatement();
- String sql="select * from "+table;
- ResultSet rs = Stm.executeQuery(sql);
- ResultSetMetaData lineInfo = rs.getMetaData();
- System.out.println("*********************RESULT META Comment************************");
- //获取数据列数
- int columnCount = lineInfo.getColumnCount();
- System.out.println("Column Count :"+columnCount);
- //获取数据列类型
- for(int i=1;i<columnCount+1;i++){
- String columeName = lineInfo.getColumnName(i);
- String columeType = lineInfo.getColumnTypeName(i);
- boolean autocol = lineInfo.isAutoIncrement(i);
- System.out.println(columeName+" = "+columeType +" ::: "+autocol);
- }
- }catch (SQLException se) {
- // 输出数据库连接错误信息
- System.out.println("SQL Exception: " + se.getMessage());
- se.printStackTrace(System.out);
- }catch(Exception e){
- System.out.println(e);
- }finally{
- try{
- con.close();
- }catch(SQLException se){}
- }
- }
- }
[java] view plain copy
- package test58;
- import java.sql.*;
- public class JDBCSTMConn{
- private static String url="";
- private static String username="";
- private static String password="";
- public Connection conn(){
- try {
- //加载JDBC驱动
- Class.forName("oracle.jdbc.driver.OracleDriver");
- //创建数据库连接
- Connection con = DriverManager.getConnection(url, username, password);
- return con;
- }catch(ClassNotFoundException cnf){
- System.out.println("driver not find:"+cnf);
- return null;
- }catch(SQLException sqle){
- System.out.println("can't connection db:"+sqle);
- return null;
- } catch (Exception e) {
- System.out.println("Failed to load JDBC/ODBC driver.");
- return null;
- }
- }
- public void execute(Connection con){
- CallableStatement toesUp = null;
- try {
- con.setAutoCommit(false);
- //调用存储过程
- toesUp = con.prepareCall("{call p_test(?)}");
- //传递参数给存储过程
- toesUp.setInt(1, 6);
- //执行存储过程
- toesUp.executeQuery();
- Statement stmt = con.createStatement();
- ResultSet rs = (ResultSet) stmt.executeQuery("SELECT * FROM TEST");
- while (rs.next()) {
- String ID = rs.getString(1);
- String NAME = rs.getString(2);
- System.out.println(ID+ " " +NAME);
- }
- rs.close();
- } catch (SQLException e) {
- System.out.println(e);
- try{
- toesUp.close();
- con.close();
- }catch(Exception es){System.out.println(es);}
- }
- }
- public void demo(){
- try{
- JDBCSTMConn oc = new JDBCSTMConn();
- Connection conn = oc.conn();
- oc.execute(conn);
- conn.close();
- }catch(SQLException se){
- System.out.println(se);
- }catch(Exception e){
- System.out.println(e);
- }
- }
- public static void main(String[] arg){
- if(arg.length!=3){
- System.out.println("use: java JDBCSTMConn url username password");
- return;
- }
- JDBCSTMConn oc = new JDBCSTMConn();
- oc.url = arg[0];
- oc.username=arg[1];
- oc.password=arg[2];
- oc.demo();
- }
- }
[java] view plain copy
- package test59;
- import java.sql.*;
- public class JDBCConnCommit{
- private static String url="";
- private static String username="";
- private static String password="";
- public Connection conn(){
- try {
- //加载JDBC驱动
- Class.forName("oracle.jdbc.driver.OracleDriver");
- //创建数据库连接
- Connection con = DriverManager.getConnection(url, username, password);
- return con;
- }catch(ClassNotFoundException cnf){
- System.out.println("driver not find:"+cnf);
- return null;
- }catch(SQLException sqle){
- System.out.println("can't connection db:"+sqle);
- return null;
- } catch (Exception e) {
- System.out.println("Failed to load JDBC/ODBC driver.");
- return null;
- }
- }
- public void query(Connection con, String sql) throws SQLException,Exception {
- try{
- if(con==null){
- throw new Exception("database connection can't use!");
- }
- if(sql==null) throw new Exception("check your parameter: 'sql'! don't input null!");
- //声明语句
- Statement stmt = con.createStatement();
- //执行查询
- ResultSet rs = stmt.executeQuery(sql);
- ResultSetMetaData rmeta = rs.getMetaData();
- //获得数据字段个数
- int numColumns = rmeta.getColumnCount();
- while(rs.next())
- {
- for(int i = 0;i< numColumns;i++)
- {
- String sTemp = rs.getString(i+1);
- System.out.print(sTemp+" ");
- }
- System.out.println("");
- }
- rs.close();
- stmt.close();
- }catch(Exception e){
- System.out.println("query error: sql = "+sql);
- System.out.println("query error:"+e);
- throw new SQLException("query error");
- }
- }
- public void execute(Connection con, String sql) throws SQLException {
- try{
- if(con==null) return;
- Statement stmt = con.createStatement();
- int i = stmt.executeUpdate(sql);
- System.out.println("update row:"+i);
- stmt.close();
- }catch(Exception e){
- System.out.println("execute error: sql = "+sql);
- System.out.println(e);
- throw new SQLException("execute error");
- }
- }
- public void demo(){
- JDBCConnCommit oc = new JDBCConnCommit();
- Connection conn = oc.conn();
- try{
- conn.setAutoCommit( false );
- String sql = "";
- for(int i=0;i<4;i++){
- sql = "insert into TBL_USER(id,name,password)values(seq_user.nextval,'tom','haorenpingan')";
- oc.execute(conn,sql);
- }
- sql = "select * from TBL_USER where name='tom' order by id";
- oc.query(conn,sql);
- sql = "delete from TBL_USER where name='tom'";
- oc.execute(conn,sql);
- conn.commit();
- }catch(SQLException se){
- try{
- conn.rollback();
- }catch(Exception e){
- }
- System.out.println(se);
- }catch(Exception e){
- System.out.println(e);
- }finally
- {
- try{
- conn.close();
- }catch(SQLException e){}
- }
- }
- public static void main(String[] arg){
- if(arg.length!=3){
- System.out.println("use: java JDBCConnCommit url username password");
- return;
- }
- JDBCConnCommit oc = new JDBCConnCommit();
- oc.url = arg[0];
- oc.username=arg[1];
- oc.password=arg[2];
- oc.demo();
- }
- }
[java] view plain copy
- package test60;
- public class oneThread extends Thread {
- public oneThread() {
- }
- public void run() {
- System.out.println("...............oneThread begining................");
- int flag = 0;
- while(true) {
- if(flag==20){
- System.out.println("\n...............oneThread end............. ");
- break;
- }
- for(int i=0;i<flag;i++)
- System.out.print("*");
- System.out.println("");
- flag++;
- try{
- //睡眠0.1秒
- sleep(100);
- }catch(Exception e){
- }
- }
- }
- public static void main(String args[]) {
- new oneThread().start();
- }
- }