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

📄 21.txt

📁 电子工业出版社出版的《java2应用开发指南》配套光盘源代码
💻 TXT
📖 第 1 页 / 共 5 页
字号:
2     import java.util.*;
3     
4     import java.sql.*;          //Package for JDBC classes
5     
6     //SQLJ package imports
7     import sqlj.runtime.*;
8     import sqlj.runtime.ref.*;
9     
10    // Iterator declaration for different streams
11    #sql iterator UnicodeIter (UnicodeStream);     
12    // Unicode format
13    #sql iterator AsciiIter   (AsciiStream asciiStream);       
14    // Ascii   format
15    #sql iterator BinaryIter  (BinaryStream binaryStream);      
16    // Binary  format
17    
18    public class sqljStreamSample {
19    
20      sqljStreamFrame m_GUI;      // The GUI handler for the sample
21      DefaultContext m_ctx;       // Holds the connection context
22    
23      /**
24    *Constructor.Initializes the JTable and other GUI components.
25      **/
26      public sqljStreamSample() {
27        try {
28           m_GUI=new sqljStreamFrame(this);
29           m_GUI.setVisible(true);
30        } catch (Exception e) {
31          e.printStackTrace();
32        }
33      }
34    
35      /**
36      * The main entry point to the application. Instantiates root 
37      * frame and database connection is made here.
38      **/
39      public static void main(String args[]){
40        sqljStreamSample SS=new sqljStreamSample();
41        //creating an instance
42        SS.dbConnection();                         
43        //connects to the database
44      }
45    
46      /**
47      * Dispatches the GUI events to the appropriate method, which 
48      * performs the required JDBC operations. This method is 
49      * invoked when event occurs in the GUI (like  Button clicks 
50      * etc.). This method is invoked from the setupListeners 
51      * section of SqljStreamFrame.java
52      **/
53      public void dispatchEvent(String p_eventName) {
54    
55        // Dispatch Event
56        if (p_eventName.equals("ASCII"))
57          readAscii();
58        else if(p_eventName.equals("BINARY"))
59          readBinary();
60        else if(p_eventName.equals("UNICODE"))
61          readUnicode();
62        else if (p_eventName.equals("EXIT"))
63          exitApplication();
64    
65      }
66    
67    
68       /**
69       *  Creates a database connection object using SQLJ. Please 
70       *  substitute the database connection parameters with 
71       *  appropriate values in ConnectionParams.java
72       **/
73       public void dbConnection(){
74    
75        try{
76          // Load the Oracle JDBC Driver and register it.
77          DriverManager.registerDriver(
78          			new oracle.jdbc.driver.OracleDriver());
79    
80          m_GUI.putStatus("Trying to connect to the Database");
81    
82          // Form the database connect string(TNSNAMES entry) as 
83          // a name-value pair using the connection parameters as 
84          // specified in ConnectionParams.java
85       String l_dbConnectString ="(DESCRIPTION=(ADDRESS=(HOST="
86							      +ConnectionParams.s_hostName+")"+
87   "(PROTOCOL=tcp)(PORT="+ConnectionParams.s_portNumber+"))"+
88  "(CONNECT_DATA=(SID="+ConnectionParams.s_databaseSID+")))";
89    
90          // To Connect to the  Oracle database, use an instance 
91          // of the DefaultContext class. The syntax of the 
92    // DefaultContext constructor is DefaultContext(databaseURL, 
93          // username,password,boolean auto-commit);
94          // The databaseURL syntax is as follows:
95          //      "jdbc:oracle:<driver>:@<db connection string>"
96          // <driver>, can be 'thin' or 'oci8'
97          // <db connect string>, is a Net8 name-value, denoting 
98          // the TNSNAMES entry
99          m_ctx = new DefaultContext(
100                     "jdbc:oracle:thin:@"+l_dbConnectString,
101                     ConnectionParams.s_userName,
102                     ConnectionParams.s_password,
103                     false);
104   
105         // Set the above connection context as the default 
106         // context for this application
107         DefaultContext.setDefaultContext(m_ctx);
108   
109       m_GUI.putStatus("Connected to "+ConnectionParams.
110         	s_databaseSID+ " as "+ConnectionParams.s_userName);
111      } catch(Exception ex){ //Trap SQL errors
112         m_GUI.putStatus("Error in Connecting to the Database "+
113    											   '\n'+ex.toString());
114       }
115     }
116   
117     /**
118     * This method reads the text from the db in ascii format
119     **/
120     public void readAscii(){
121      try{
122       // Display the file contents in TextArea and get the text 
123       // to be converted
124       String l_str=m_GUI.displayText(10);
125   
126       AsciiIter l_ascii=null;        
127       // Declare the iterator to retrieve the stream
128       AsciiStream l_asciiStream=null;
129       //Stream declaration to read ascii data
130   
131       // The query selects a string from the dual table
132       #sql l_ascii={ SELECT :l_str asciiStream FROM dual };
133   
134       // Open the iterator and obtain the AsciiStream handle
135       l_ascii.next(); // Point to the row retrieved
136     l_asciiStream=l_ascii.asciiStream();//Get the AsciiStream
137   
138       int l_read;   // Character read from stream
139       int l_cnt=0;  // Counter to enable wrapping after 10 chars.
140   
141       // Loop through the stream, read and display each character
142       while((l_read= l_asciiStream.read()) != -1){
143         m_GUI.padAndAppend(l_read,"|"); 
144         // Print the obtained character in GUI
145         // Wrap after 10 characters
146         ++l_cnt;
147         if (l_cnt==10) {
148            l_cnt=0;
149            m_GUI.m_textarea1.append("\n");
150         }
151       }
152       l_asciiStream.close(); //Closing the stream
153       m_GUI.clearStatus();
154      }catch(Exception ex){
155        m_GUI.putStatus("The exception is " + ex.toString());
156      }
157   
158     }
159   
160     /**
161     * This method reads string from the db and displays in the 
162     * binary format.
163     **/
164     public void readBinary(){
165       try{
166         // Display the file contents in TextArea and get the text 
167         // to be converted
168         String l_str=m_GUI.displayText(10);
169   
170         BinaryIter l_binary=null;       
171         //Declare the iterator to retrieve the stream
172         BinaryStream l_binaryStream=null;
173         //Stream declaration to read binary data
174   
175         // The query selects the file contents from the database, 
176         // using a select <text> from dual SQL command.
177         #sql l_binary={ SELECT :l_str binaryStream FROM dual };
178   
179         // Open the iterator and obtain the BinaryStream handle
180         l_binary.next(); // Point iterator to the row retrieved
181         l_binaryStream=l_binary.binaryStream(); 
182         // Obtain the Binary Stream
183   
184         int l_read;   // Character read from stream
185         int l_cnt=0; //Counter to enable wrapping after 10 chars.
186   
187        // Loop through the stream, read and display the character
188         while((l_read= l_binaryStream.read()) != -1){
189  m_GUI.m_textarea1.append(Integer.toHexString(l_read)+"|");
190   
191           // Wrap after 10 characters
192           ++l_cnt;
193           if (l_cnt==10) {
194             l_cnt=0;
195             m_GUI.m_textarea1.append("\n");
196           }
197         }
198         l_binaryStream.close();   //Closing the binary stream
199         m_GUI.clearStatus();
200       } catch(Exception ex){
201         m_GUI.putStatus("The exception is " + ex.toString());
202       }
203     }
204   
205     /**
206     * This method reads string from the db and displays in the 
207     * unicode format.
208     **/
209     public void readUnicode(){
210       try{
211   
212         // Display the file contents in TextArea and get the text 
213         // to be converted
214         String l_str=m_GUI.displayText(6);
215   
216         UnicodeIter l_unicode=null; 
217         // Declare the iterator to retrieve the stream
218         InputStream l_unicodeStream=null; 
219         //Stream declaration to read unicode data
220   
221         // The query selects the file contents from the database, 
222         // using a select <text> from dual SQL command
223         #sql l_unicode = { SELECT :l_str FROM dual };
224   
225         // Convert UnicodeIter to a ResultSet and obtain the 
226         // UnicodeStream handle
227        ResultSet l_resultset=l_unicode.getResultSet();
228         l_resultset.next(); // Point to the retrieved row
229         l_unicodeStream=l_resultset.getUnicodeStream(1); 
230         // Get the Unicode Stream
231   
232         int l_read;   // Character read from stream
233         int l_cnt=0; //Counter to enable wrapping after 10 chars.
234   
235         // Loop through the stream, read and display both bytes 
236         // of unicode
237         while((l_read=l_unicodeStream.read()) != -1){
238           // Print the first byte of the Unicode character
239           m_GUI.padAndAppend(l_read, " "); // Print in GUI
240   
241           // Retrieve and print the second byte of Unicode
242           m_GUI.padAndAppend(l_unicodeStream.read(),"|");
243   
244           // Wrap after 10 characters
245           ++l_cnt;
246           if (l_cnt==6) {
247             l_cnt=0;
248             m_GUI.m_textarea1.append("\n");
249           }
250         }
251         m_GUI.clearStatus();
252         l_unicode.close(); //Closing the iterator object
253         l_unicodeStream.close();  //Closing the unicode stream
254       } catch(Exception ex){
255         m_GUI.putStatus("The exception is " + ex.toString());
256       }
257     }
258   
259     /**
260      *  This method closes the connection object before exiting 
261      * the application
262     **/
263   
264     public void exitApplication(){
265       try{
266         if(m_ctx!=null){
267           m_ctx.close();  //closing the connection context
268         }
269       }catch(SQLException ex){ //Trap SQL Errors
270         m_GUI.putStatus(ex.toString());
271       }
272       System.exit(0);
273     }
274   
275   }
例程21-11
1    import java.awt.*;
2    import java.io.*;
3    import java.awt.event.*;
4    import java.util.*;
5    
6    /** Use the following import statements with
7    			 SWING version 1.0.2   **/
8    //import com.sun.java.swing.*;
9    
10   /** Use the following import statements with
11   			 SWING version 1.1   **/
12   import javax.swing.*;
13   
14   public class sqljStreamFrame extends JFrame {
15   
16     sqljStreamSample m_parent;
17     static String s_fileName = "information.txt";
18   
19     //Icon object whichholds a image files
20     ImageIcon m_radio, m_radioPressed, m_radioSelected;
21   
22     TextField m_statusbar = new TextField();           
23     //Status bar
24     JPanel m_panel1, m_panel2, m_panel3, m_radioPanel; 
25     //Jpanels
26     JLabel m_label1, m_label2, m_label3;               
27     //Labels used in the UI
28     TextArea m_textarea1, m_textarea2;  
29     //TextArea for displaying the output
30   
31     //Buttons for specifying the operations to be performed
32     JRadioButton m_ascii, m_unicode, m_binary, m_exit;
33   
34     //ButtonGroup for holding the Radio Buttons
35     ButtonGroup m_group=new ButtonGroup();
36   
37     //Layout manager which layout the components
38     GridBagLayout m_gridBagLayout1, m_gridBagLayout2,
39     					 m_gridBagLayout3;
40     BorderLayout m_borderLayout1   = new BorderLayout();
41   
42    /**
43   *Constructor. Initializes the JTable and other GUI components.
44    **/
45     public sqljStreamFrame(sqljStreamSample p_parent){
46       try{
47         m_parent=p_parent;
48         jbInit();         //GUI components initializations
49       setupListeners(); //Setting up event listeners and actions
50       }catch (Exception ex){ //Trap General Errors
51         putStatus("Error...!!! "+ ex.toString());
52        }
53     }
54   
55     /**
56     * Retrieve the File contents and display the contents in the 
57     * GUI TextArea p_numChars : Number of characters after which 
58     * to wrap
59     **/
60     public String displayText(int p_numChars) {
61       m_textarea2.setText("");
62       try {
63         FileInputStream l_fis=
64         	new FileInputStream(new File(s_fileName)); // Open file
65         int l_dataread=0;
66         StringBuffer l_strbuf=new StringBuffer();
67         int l_cnt = 0;
68   
69         // Loop through the file, save in stringbuffer and also 
70         // write to GUI
71         while((l_dataread = l_fis.read()) != -1) {
72           Character l_read = new Character((char)l_dataread);
73           if (!l_read.toString().equals("\n")) {
74             l_strbuf.append(l_read.toString());
75             m_textarea2.append(l_read.toString()+"|");
76   
77             // Wrap after p_numChars
78             l_cnt++;
79             if (l_cnt == p_numChars) {

⌨️ 快捷键说明

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