⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 clientfactory.java

📁 SQL Plus是一款通用数据库操纵、存取程序
💻 JAVA
📖 第 1 页 / 共 2 页
字号:
		
		cmd = "select * from " + cmd + " where 1<>1"; // re group the sql
		
		java.sql.PreparedStatement ps = conn.prepareStatement(cmd);
		
        java.sql.ResultSet rs = ps.executeQuery(); //取得当前记录的最大值
        
        java.sql.ResultSetMetaData rmd = rs.getMetaData();
        try{
	        // Print Header
	        int[] width = {45, 16, 12};
	        // print names
	        System.out.print("Field Name");
	        for(int j = 0; j < width[0] - "Field Name".length(); j++)
	        	System.out.print(" ");
	        System.out.print(" Var Type");
	        for(int j = 0; j < width[1] - "Var Type".length(); j++)
	        	System.out.print(" ");
	        System.out.print(" Is NULL");
	        for(int j = 0; j < width[2] - "Is NULL".length(); j++)
	        	System.out.print(" ");        	
	        System.out.print("\r\n");	
	        // ----
	        for(int j = 0; j < width[0]; j++)
	        	System.out.print("-");
	        System.out.print(" ");
	        for(int j = 0; j < width[1]; j++)
	        	System.out.print("-");
	        System.out.print(" ");
	        for(int j = 0; j < width[2]; j++)
	        	System.out.print("-");        	
	        System.out.print("\r\n\r\n");	
	        
	        // Values   	
	        for(int i = 1; i <= rmd.getColumnCount(); i++)
	        {
	        	String cname = rmd.getColumnName(i); // 列名
	        	int   icname = cname.toCharArray().length; // char width
	        	if(icname < width[0])
	        	{
	        		System.out.print(cname);
	        		for(int j = 0; j < width[0] - icname; j++)
	        			System.out.print(" ");
	        	}
	        	System.out.print(" ");
	        	cname = rmd.getColumnTypeName(i); // 类型名
	        	if(cname != null && (cname.toUpperCase().startsWith("VARCHAR") || cname.toUpperCase().startsWith("CHAR")))
	        		cname += "(" + rmd.getColumnDisplaySize(i) + ")";
	        	icname = cname.toCharArray().length; // char width
	        	if(icname < width[0])
	        	{
	        		System.out.print(cname);
	        		for(int j = 0; j < width[1] - icname; j++)
	        			System.out.print(" ");
	        	}
	        	System.out.print(" ");
	        	int isn = rmd.isNullable(i); // 是否为空
	        	cname = "Not NULL";
	        	if(isn == 1)
	        		cname = "    ";
	        	icname = cname.toCharArray().length; // char width
	        	if(icname < width[0])
	        	{
	        		System.out.print(cname);
	        		for(int j = 0; j < width[2] - icname; j++)
	        			System.out.print(" ");
	        	}
	        	System.out.print("\r\n");
	        }
	        
			System.out.print("\r\n------------------\n" + rmd.getColumnCount() + " Columns Show OK!\r\n\r\n");
		}catch(SQLException e){
			throw e;
		}finally{
			try{
			// clear
				if(rs != null)rs.close();
				if(ps != null)ps.close();
			}catch(Exception e){}
		}
	}
	/**
	 * method connect()
	 * <br>
	 */
	private void connect() throws SQLException, ClassNotFoundException
	{
		Class.forName(jdbc);
		if((user == null && pass == null)|| ("".equals(user.trim()) && "".equals(pass.trim())))
			conn = (java.sql.Connection)DriverManager.getConnection(url);			
		else
        	conn = (java.sql.Connection)DriverManager.getConnection(url, user, pass);
		log("\r\nConnected.\r\n");
	}
	/**
	 * method log<br>
	 * print information on control platform
	 */
	private void log(String info)
	{
		System.out.println(info);
	}
	/**
	 * Method savepoint(sname)
	 *
	 * Save rollback point
	 */
	private void savepoint(String sname)throws SQLException
	{
		isClosed(); // 连接是否关闭
		
		if(sname != null)
		{
			Savepoint sp = conn.setSavepoint(sname);
			
			// 是否已经设置了这个回滚点
			if(hm.containsKey(sname))hm.remove(sname);
			// 加入到回滚有名列表
			hm.put(sname, sp);
		}
		else
			conn.setSavepoint();
		
		log("Save Point Success.\r\n");
	}
	/**
	 * Method rollback(sname)
	 * <br>回滚
	 */
	private void rollback(String sname)throws SQLException
	{
		isClosed(); // 连接是否关闭
		
		if(sname != null)
		{
			if(hm.containsKey(sname))
			{
				Savepoint sp = (Savepoint)hm.get(sname);
				hm.remove(sname);
				conn.rollback(sp);
			}
		}else
		{
			conn.rollback();
		}
		
		log("Roll Back Save Point '" + sname == null?"":sname + "' Success.\r\n");
	}
    /* (non-Javadoc)
     * @see com.ora.db.Client#importIPDB(java.lang.String)
     */
    public void importIPDB(String mdb, String table, String totable, String fin, String tin) {
        String aurl = "jdbc:odbc:driver={Microsoft Access Driver (*.mdb)};DBQ=" + mdb;
        PreparedStatement ps = null;
        ResultSet rs = null;
        Connection tconn = null;
        try {
            Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
            tconn = (java.sql.Connection)DriverManager.getConnection(aurl);	            
            ps = tconn.prepareStatement("select "+fin+" from " + table);
            rs = ps.executeQuery();
            String sql = "insert into "+totable+" ("+tin+") values(?,?,?,?)";
            long i = 0;
            System.out.print("\r\nPlease Waiting The System is import the ips to dest database...\r\n\r\n");
            PreparedStatement pst = conn.prepareStatement(sql);
            while(rs.next())
            {                
                try{
	                pst.setLong(1, rs.getLong(1));
	                pst.setLong(2, rs.getLong(2));
	                String ss = rs.getString(3);
	                String sm = rs.getString(4);
	                if(ss == null || "".equals(ss))ss = " ";
	                if(sm == null || "".equals(sm))sm = " ";
	                pst.setString(3, ss);
	                pst.setString(4, sm);
	                pst.executeUpdate();
	                i ++;
                }catch(Exception ee){
                    ee.printStackTrace();
                    System.out.print("\r\nInsert Error: " + ee.getMessage() + "\r\n\r\n");
                }
                finally{
                    
                }                
            }
            try{
                pst.close();
            }catch(Exception eee){}
            System.out.print("\r\n" + i + " IPs has been input to dest table "+totable+".\r\n\r\n");
        } catch (Exception e) {
           //e.printStackTrace();
            System.out.print("\r\nError: " + e.getMessage() + "\r\n\r\n");
        } finally{
            try{
                rs.close();
            }catch(Exception eee){}
            try{
                ps.close();
            }catch(Exception eee){}
            try{
                tconn.close();
            }catch(Exception eee){}
        }
    }
    /**
     * 采用多线程处理
     * @param mdb
     * @param table
     * @param totable
     * @param fin
     * @param tin
     * @param threads
     */
    public void importIPDB(String mdb, String table, String totable, String fin, String tin, int threads) {
        String aurl = "jdbc:odbc:driver={Microsoft Access Driver (*.mdb)};DBQ=" + mdb;
        PreparedStatement ps = null;
        ResultSet rs = null;
        Connection tconn = null;
        try {
            Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
            tconn = (java.sql.Connection)DriverManager.getConnection(aurl);	 
            String mc[] = fin.split(",");
            
            ps = tconn.prepareStatement("select min("+mc[0]+"),max("+mc[0]+"),count(1) from " + table);
            rs = ps.executeQuery();
            String sql = "insert into "+totable+" ("+tin+") values(?,?,?,?)";
            long i = 0;
            int j = 0;
            long min = -1;
            long max = 0;
            System.out.print("\r\nPlease Waiting The System Start some threads to import the ips to dest database...\r\n\r\n");
            if(rs.next())
            {
                min = rs.getLong(1) - 1L;
                max = rs.getLong(2) + 1L;
                i = rs.getLong(3);
                long block = (max - min) / (long)threads;
                IPImportThread ips[] = new IPImportThread[threads];
                for(j = 0; j < threads; j++)
                {
                    long start = j * block + 1;
                    if(j == 0)start = -1;
                    long end = (j+1L) * block;
                    String sqlf = "select "+fin+" from "+table+"  where "+mc[0]+" between "+start+" and " + end;
                    //System.out.print(sqlf);
                    ips[j] = new IPImportThread(jdbc, url, pass, user, aurl, sqlf, sql, "Processor " + (j+1));
                    Thread t = new Thread(ips[j]);
                    t.start(); // 启动一个线程。
                }
                new Thread(new Runnable(){
                    private IPImportThread[] iis;
                    public Runnable setAll(IPImportThread[] iis){
                        this.iis = iis;
                        return this;
                    }
                    public void run() {
                        boolean hasOK = true;
                        double t = (double)System.currentTimeMillis();
                        while(hasOK)
                        {
                            hasOK = false;
                            for(int i = 0; i < iis.length; i++)
                            {
                                if(!iis[i].hasOver)
                                {
                                    hasOK = true;
                                    break;
                                }
                            }
                            try {
                                Thread.sleep(1000);
                            } catch (InterruptedException e) {
                                
                            }
                        }  
                        long total = 0;
                        for(int i = 0; i < iis.length; i++)
                        {
                            total += iis[i].total;
                        }
                        System.out.println("\r\n"+total+" Ips Imported Success, Take "+(((double)System.currentTimeMillis() - t)/1000D/60D)+" minutes totally.");
                    }}.setAll(ips)).start();
            }
            System.out.print("\r\n" + i + " IPs will be input to dest table "+totable+".\r\nHave "+j+" Threads Processor is processing.\r\n\r\n");
        } catch (Exception e) {
           //e.printStackTrace();
            System.out.print("\r\nError: " + e.getMessage() + "\r\n\r\n");
        } finally{
            try{
                rs.close();
            }catch(Exception eee){}
            try{
                ps.close();
            }catch(Exception eee){}
            try{
                tconn.close();
            }catch(Exception eee){}
        }
    }
    
    public class IPImportThread implements Runnable{
        private String driver;
        private String url;
        private String pass;
        private String user;
        
        private String urlFrom;
        private static final String driverFrom = "sun.jdbc.odbc.JdbcOdbcDriver";
        private Connection tconn = null;
        private Connection fconn = null;
        private String sqlIn;
        private String sqlOut;
        private String name = "Processor";
        public boolean hasOver = false;
        public long total = 0;
        /**
    	 * method connect()
    	 * <br>
    	 */
    	private void connect() throws SQLException, ClassNotFoundException
    	{
    		Class.forName(this.driver);
    		if((this.user == null && this.pass == null)|| ("".equals(this.user.trim()) && "".equals(this.pass.trim())))
    			tconn = (java.sql.Connection)DriverManager.getConnection(this.url);			
    		else
            	tconn = (java.sql.Connection)DriverManager.getConnection(this.url, this.user, this.pass);    		
    		Class.forName(driverFrom);
    		fconn = (java.sql.Connection)DriverManager.getConnection(this.urlFrom);	    
    	}
        
        public IPImportThread(String dr, String u, String ps, String us, String uf, String in, String out, String name) throws SQLException, ClassNotFoundException
        {
            this.driver = dr;
            this.url = u;
            this.pass = ps;
            this.user = us;
            this.urlFrom = uf;
            this.sqlIn = in;
            this.sqlOut = out;
            this.name = name;
            connect();
            hasOver = false;
        }
        /* (non-Javadoc)
         * @see java.lang.Runnable#run()
         */
        public void run() {
            PreparedStatement ps = null;
            ResultSet rs = null;
            try {         
                ps = fconn.prepareStatement(sqlIn);
                rs = ps.executeQuery();
                //long i = 0;
                //System.out.println("\r\nSQL:" + sqlIn);
                System.out.print("\r\nPlease Waiting The Thread "+name+" will import the ips to dest database...\r\n\r\n");
                PreparedStatement pst = tconn.prepareStatement(sqlOut);
                //System.out.print(sqlOut);
                while(rs.next())
                {                
                    try{
    	                pst.setLong(1, rs.getLong(1));
    	                pst.setLong(2, rs.getLong(2));
    	                String ss = rs.getString(3);
    	                String sm = rs.getString(4);
    	                if(ss == null || "".equals(ss))ss = " ";
    	                if(sm == null || "".equals(sm))sm = " ";
    	                pst.setString(3, ss);
    	                pst.setString(4, sm);
    	                pst.executeUpdate();
    	                total++;
                    }catch(Exception ee){
                        ee.printStackTrace();
                        System.out.print("\r\nInsert Error: " + ee.getMessage() + "\r\n\r\n");
                    }
                    finally{
                        
                    }                
                }
                System.out.println("\r\n"+total+" IPs imported. Thread : " + this.name + " ended.\r\n");
                try{
                    pst.close();
                }catch(Exception eee){}
            } catch (Exception e) {
               //e.printStackTrace();
                System.out.print("\r\nError: " + e.getMessage() + "\r\n\r\n");
            } finally{
                try{
                    rs.close();
                }catch(Exception eee){}
                try{
                    ps.close();
                }catch(Exception eee){}
                try{
                    tconn.close();
                }catch(Exception eee){}
                try{
                    fconn.close();
                }catch(Exception eee){}
            }
            hasOver = true;
        }
        
    }
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -