C A c H E - C O N T R O L refers to the operation of the specified cache system to the document. The most common value is: no - cache (indicating this document does not need to cache), no - store (indicating that this document does not have to cache, do not save in the proxy server, usually sensitive), max - agn = seconds (indicate document The length of time is reached.). This head is from http 1. 1 to introduce P ragma refers to the equivalent ahead of HTTP 1. 0 is C Ache - Control, and only one possible value NO - CACH EC ONNECTION means that the server is willing to continue to connect to customers . If desirable, its value is set to k e e p - a L i v e; otherwise set to C L O S e. Most of the server depends on their servlet. When the servlet sets the c ontent -l ength head, the server automatically sets the value of c onnection to Keep - Aliv er etry - a fter refers to the time that the server can process the request again. , Use with the SC _ SE RV ICE _ UN AVA ILABLE status code. Its value either represents an integer of time (seconds), or it represents the date substring representing the actual time. E x p i r e s refers to when a document may change, or its information will become illegal. It also means that before this time, the document is not possible to change the new path to the specified document, which is usually used with SC_MOVed_Premanently and S c_moved_premanently and S c_m o V e-T E M P O R A R I LY. Its value must be a complete U r L (including "H T T P: / / / /") W W W W- A U TET HE E N T I C A TE EN NGE specifies the authentication system and authentication range required by the customer requirements of the access request URL. The C O N T E N T - E N C O D i N g is used to specify the system for encoding the responsive body. The possible values are: g z I p (or x - g z I p), C O m P R e s S (or X -C O M P R E S S). The multi-encoding system should be used in a comma-separated (1) to set the H t t p-head H t t p S E R V1, which provides a series of methods, helping S e R V1 T t, in order to help S e R Vl E t set the H t t p-response header information. The head value can be set using the S e T HE E R () method: public void httpservletResponse.setHeader (String name, string value) This method sets the value of the specified head to S t R I n g. This name is constant, the same is true for all methods. If the value of the head has been set, the new value will overwrite the previous value. All types of heads can be set by this method.
If you need to define a date stamp for header, you can use the SET D ATE H EADER () method: public void httpservletResponse.setDateHeader (String name, long Date) This method sets the header value of the specified name to a specific date and time. And receive the LONG type value of the date (indicating the number of milliseconds from GMT 1970, 1, 1, 0: 0: 0). If this head has been set, the new value will overwrite the old value. Finally, you can specify a integer value with the SET I NT H EAder (): Public Void HttpservletResponse.setInTheader (String Name, INT Value) This method sets the value of the head to integers, if you have already set it, The value covers the old value. C O N T A I N S HE E A D ER () method provides a way to check whether the head is present: public boolean httpservletResponse.containsheader (String name) If the header has been set, this method returns T R u E, otherwise returns F A L s E. In addition, H T M L 3. 2 specification, there is another method of setting a head value: using an embedded
For static documents, they don't have to access their headers. (2) Another use of the redirection request S e R Vl e t using the status code and header information is to redirect requests. This is achieved by sending another U r L indication to the client. Redirection is typically used in: When the document moves (send a new path to the client), the load balance (a U r1 may be distributed on several different machines), simple random documents (randomly select the target path). Real redirection occurs in two lines: res.SC_MOVED_TEMPORARILY; Res.SetHeader ("Location", Site); The first line sets the status code, indicating that the need to redirect, the second line gives a new location . To make sure they work properly, these methods must be called before sending any output. Remember, the H t t p protocol sends a status code and header information before sending the content body. The location of the new site must be given in absolute U R L (for example, H t t / / / / / / / / / / / / / / / f i l e. H t m l), otherwise, customers are difficult to find. The use of Send R eDirect () methods can easily simplify the two lines into one line: public void httpservletResponse.sendRedirect (string location) throwsioException This method redirects the response information to the new location, automatically set the status code and the head of the status code and L ocation Information, these two lines become: res. extendedRedirect (Site); (3) Customer traction customer traction and redirect is similar, the main difference is that the browser has always displayed the content of the first page, and the second Page before waiting for a specified time interval. It is called customer traction because it is dragged by the client. What is this? First, you can tell the content of the request from the first page before the second page, and the web page can be received in order, providing a possible slow page animation. Customer traction information is sent to the client using the Refresh HTTP header. This head value indicates the number of seconds of the current page before pulling the next page, or selectively contains a U r L substring, from the file. If no U r L is given, the same U r L is used. Below this statement tells customers that after displaying the current content 3 S, re-establish servlet: setHeader ("Refresh", "3"); here there is a statement that tells the customer 3 S after displaying N etscape homepage: setHeader ("refresh" , "3; URL = http: //Home.Netscape.com"); 7. Error handling servlet sometimes error, does not matter, servlet must have errors, there is expected, and there are unexpected. Error Once, you must care about two things: 1) The destruction of the server is minimized. 2) Correct notification client. Since SE R Vl e t is written in J A V A, it is greatly reduced to the server's destruction.
The server can securely embed S E R V L e t (even in its process), just like the WE B browser can securely embed the A p L e t s. This security is based on the security system of J a V A, including protecting memory usage, exception handling, security management mechanism, etc. Inside the J a V A of the JSP Getting Started
Polish protection ensures that the servlet cannot occasionally (or deliberately) access the internal system of the server; the exception handling of J ava enables the server to capture every exception caused by the servlet, even if servlet is zero, or call the method of empty objects, the server It is still able to continue to work; J AVA's security management mechanism provides a server for the server to put trusted servlets in a sandbox, limits and prevents them from deliberately destroying the capabilities. It should be cautious that servlets running outside the security manager have the ability to damage server damage, and servlet may cover the server's file space or even call S Ystem. EXIT (), you should believe that trusted servlet is generally The server is damaged, and S Ystem is rarely called. EXIT (). The problem that appears correctly to the customer is not only the J a v A language, but there are many factors that need to be considered: 1) How to tell the client? S-E R V L E T sent a normal status code error page to the client, or sends an error literal, or send the error stack details? 2) How to record the problem? Is it saved to a file, written to the server log, or ignored? 3) How to recover? S-e r v l e t Continued to deal with the next request? Or S e r v L e t crash, this means that it must be re-. The answers to these issues depends on S E R V L e t and its use. How to deal with the error is determined by the developer himself, but it should ensure that the reliability and robustness of S E R V L e t is requested. Next, look at the entire picture of the S E R V L e t error handling mechanism, and you can choose to use them to implement an error handling policy. (1) Status code S e R V L e t simplely error modified method is to transmit an appropriate 4 0 0 series or 5 0 0 series state code with SE N D E R R () method. For example, when S e r v L e t is requested to be a non-existing file, it can return S c_ n o t_ f O u n D; if the request is exceeded, it can return to S c_ n o t_ i m p L e m e n t e D. When internal exception occurs, it can return to S c _ i n t e R n a L _ S e RV E R _ E R R O R. By using the status code, S e r v L e t provides a chance to respond special processing of the response information. For example, some servers can replace the response information of the servlet, such as the server-related error message; if the error should be explained by the servlet, it can use the set s tatus () to set the status code while issue a corresponding response Body, this responsive body can be text format, image format, and other appropriate types. S-E R V L e t should be captured and processed as possible before the response body is transmitted. You may still remember (because we repeatedly mentioned), the H t t p specified status code and the H t t p header must be sent before responding. Once a response message is issued, even if only one character is issued, it will not change the status code and the H t t p header information. To avoid this "too late" embarrassing situation, you can use B Y T E A R R A Y O U T P U T M L Builder Pack.
(2) Log servlets can write their behavior and errors to write to log files using the log () method: public void servletcontext.log (String MSG) Public Void ServletContext.log (Exception E, STRING MSG) method of single parameter is Write a given message into the servlet log, this log is usually an event log file. The version with two parameters is to write a given message and exception stack information into the S E R V L E T log. The output format of these two methods and the path of the second chapter of the Login preparatory knowledge is related to the server. G ENERIC SERVLET class also provides a log () method: public void genericservlet.log (String MSG) This is another version of the SERVLET C onText method, which is used in the G ENERIC SERVLET class, this method allows servlet Simple calls like this, write to the servlet log: log (msg); however, G ENERIC SERVLET does not provide a log () version of the two parameters, which may be negligent, which will increase in future versions. Now, S e r V L e t can perform similar functions by calling the following functions: GetServletContext (). Log (e, msg); L O g () method provides a way to track S E R V L E T behavior and can be used to help programs debugging. It also provides a false detailed description method that holds any faults encountered by S E R V L E T, which may be more detailed as transmitted to the client. (3) Report error In addition to the server administrator records errors and abnormalities, it is also convenient to show the problem in the development process. Unfortunately, the exception cannot return its stack tracking information in the form of S T R I N g, which can only display stack tracking information to P R i N t R E A M or P R I n T WR I T ER. To collect stack tracking information with the S t R I n g, you must take a few more than a few. An exception must be displayed in a special P R i N T WR I T ER, which is based on B Y T R RR R A Y O U T P U t, which can capture the output and converted to S T R I N g based.
... Com oreill y servlet S ervlet U tils class has get S tack Tr ace S tring () method to accomplish this work: public static String getStackTraceAsString (Exception e) {ByteArrayOutputStream bytes = new ByteArrayOutputStream (); PrintWriter writer = NEW PrintWriter (Bytes, true); E.PrintStackTrace (Writer); Return Bytes.toString ();} The following is a VI EW f Ile: file: // return the file {servletUtils.ReturnFile (ServletUtils.ReturnFile) ( File, out);} catch ("could not find file:" E.GETMESSAGE ()); res.Sc_not_found;} catch (ioException e) {GetServletContext (). log (e, "problem sending file"); res. scrub_internal_server_error, servletils.getstacktracesstring (e));} (4) Exception Processing I have mentioned that the exception thrown will be captured by the servlet, Server capture. How does the server handle an exception that is different from the server: it may send a message and stack tracking information to the client; it may automatically record an exception; it is very 52 first part JSP entry
The D e S r o y () method is perhaps the D e S t R o y () method is also raised. The SE R V L e t designed and developed for a particular server can optimize the behavior of the server, and cannot do not until S e R V L e t spanning multiple servers. If this S e R V L e t requires special exception processing, it is necessary to consider the corresponding server factor. Some exception types are that S e r V L e t must capture, and S e R V L E T can only pass I O e x C e p TE I O N, S E R V1 E TE E X C E P T I O N or R u N T I m E E X C E P T I O N sub-class abnormality to its server. Causes and methods are related to the method of the method, the S e R V i c e () method of S e r V L e t is declared in its T H R O W S statement to throw I O e x C e p T I O N abnormality, so it does not capture the abnormality during the compilation process. R u N t I m e e x c e p T I o n is a special type of abnormality, which does not need to be declared in the T H R O W S statement, and a common example is N u L P O I N t e x C e P T I O n. The I n i t () method and the D e S t R o y () method also have its own feature, I n i t method declaration only throws only S E R V L E TE E X C E P T I O N abnormality, and the D e S T R O Y () method declares does not throw an abnormality. S E R V L E TET is a subclass of J A V a. L A N g. E x C e p T I O N, which is defined in J A X. S E R V L E T. P a c k A g E Packet is defined. This exception indicates the problem of conventional S e r V L e t, which has the same constructor as J x C e p t i o n: one without parameters, one message string parameter. Capturing this anomalous server may handle it with any suitable method. J a v a x. s E R V L E T Pack defines a S e R V L E TEE X C e P T I O N sub-class U N A V A I L A B LEE E X C E P T I O N, which indicates that S E R V L e t is inaccessible, or temporary, or permanent. U navailable E xception has two constructors: java.servlet.UnavailableException (Servlet servlet, String msg) java.servlet.UnavailableException (int Seconds, Servlet servlet, String msg) two-parameter constructor to create a new exception, indicates that the specified Servlet is permanently inaccessible, and is given by MSG; the three-parameter constructor creates a new exception, indicating that the specified servlet is temporarily unacceptable, and is given by the MSG, and the length of time that is not accessible is given by seconds. This is just an estimated time.
2.4 SQL Language JSP database depends on JDBC, and the power of JDBC is that JDBC can make J ava a powerful tool that can be dealt with uneven database environments, this uneven database environment, despite the difference Big, but no matter which relational database, from o Racle to DB 2 to S YBase to MS SQL Server, it is the same, that is, SQL language - structured query language. Although different database vendors have made their own extensions, such as: o racle's PL - SQL, Microsoft SQLS ERVER TR AnsAct - SQL, and SQL language Nasal IBM DB2 SQL, each RDBMS manufacturer claims her own The extension is the best, however, these different SQL still have a common point, they are all based on ANSI SQL 92. SQL is not a particularly complex language, but if you want to learn SQL, especially the unique SQL-specific SQL, there is still a special effort, just tell the most basic statement in SQL, this book is also in the example program in the first part. Will only use the most basic SQL statement, in the example of the second part, since the stored procedure will be used, these extensions will be explained again when needed. 2.4.1 Subtypes of SQL Sub Type S Q L Language include: Data Processing Language (D m L), Data Definition Language (D D L) and Data Control Language Chapter 2 Preparation Knowledge 53
(D C L). Data Processing Language DML is done in the database to determine, modify, add, delete a value of a value of a certain amount of data. The following is some of the data processing SQL statements that are often used in J AVA and JDBC: SELECT in the database according to a certain rule query data. I N s e rt adds a line of data to the database. Delete Deletes a row of data in the database. U P D ATE changes the record in the database. Data Definition Language D l Complete the structure of the defined database, including database itself, data table, directory, view, and other database elements: C R e ATE creates an element in the database. DROP deletes an element in the database. Data Control Language DCL Completes the task of the storage permission in the management database, the following is some data control SQL statements that are often used in J AVA and JDBC: GRANT Sets a user or user group can access some form to access some of the database element. Revoke removes the right of a user or user group to access a certain element in a form of a database. 2.4.2 SQL language Specific commands and use the following example uses the sample database comes with Microsoft SQL Server 7.0, which needs to be explained, although Microsoft SQL Server is supported by J ava than other RDBMS such as O racle, DB 2 It is more likely to use, but Microsoft SQLS ERVER is easier to use. This book is basically established by the example of the first part; on the other hand, the first part of the example does not use the SQL Server unique SQL statement, Therefore, the reader can transplant these examples to O Racle, DB 2 or any other database system that supports SQL. 1. SELECT statement select is undoubtedly the most commonly used statement in the SQL statement, and a SELECT statement can be very simple, or it can be very complex. From the simplest start: Select the database in Query Analyzer to n Orthwind, then enter: SELECT * From customer executive, you can see the results shown in Figure 2 - 1: This SELECT statement has a very well understood from the literal, ie, from the Customers data table, "*" represents all Column. If "*" is changed to "c ustomer id", the result will become: Customerid ---------- Alfkianatranton..................................................................................... No longer use graphical representation, readers should understand. 54 Part 1 JSP Getting Started
The contents in Figure 2 - 1 "*" can also contain multiple items, with "," separated, such as "Select Customerid, CompanyName from Customers". (1) The name of a column in a column using the alias data table should be meaningful, but unfortunately, this is only for some people, and there is often this situation: a database created by a bit of database contains The column name is clear for himself, but it is an unknown cloud for others. The solution is to establish an alias for a column of the data sheet when query. ----------------------------------- 0 3 0 - 0 0 7 4 3 2 1 0 3 0 - 0 0 7 6 5 4 5 (5) 555-4729 (5) 555-3745 (5) 555-3932 Nul L.... In this way, I don't know if I don't know English. Phone "and" Fax "now become simple and easy to understand the second chapter preparatory knowledge 55
"Phone" and "Fax". (2) Add text to the query output although the output after the above additional alias is easy to understand, it is still not clear, and the method of adding text in the query output will output a complete sentence. Select CompanyName AS "Company Name", "Company's Phone is", Phone AS "Phone" from customer's result is: Company Name Phone ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ ------------------------------------------------- ------------------------ Alfreds Futterkiste's phone is 0 3 0 - 0 0 7 4 3 2 1NA Trujillo Emparedados YELADOS company phone is ( 5) 555-4729 daonio Moreno TA Que Ría's phone is (5) 555-3932........................................................... The web page contains the Query results of the HTML code. (3) The role of the ORDER BY clause ORDER BY clause is to arrange the output as a column in ascending or descending order, where the additional command of the ascending arrangement is ASC, and the additional commands arranged in the descending order are DESC, the default is ascended as ascending . Select CompanyName, Phone from Customers Order by Phone results are as follows: C OMPANY N Amephon E -------------------------- ------- ----------------- Maison Demey (02) 201 24 67S Up rêmes délices (071) 23 67 2220 runto grande (1) 123-5555 and if it is: Select CompanyName, Phone The result of from customer desc is: C OMPANY N Amephon E ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ ------------------ Wartian Herkku 9 8 1 - 4 4 3 6 5 5Bon APP '9 1. 2 4. 4 5. 4 0wilman Kala 90-224 8858 (4 Where phrase where is a text of a conditional selection data, which specifies only the data consistent with the WHERE phrase. The condition of the W H e R e phrase can include relationship operation, Boolean operation, L i k e, i n, b e t w e n, etc., and even the query results of other S E L E C T statements. The following introduces: 56 Part 1 JSP Getting Started
1) Relationship operation. The relationship between S Q L language includes: "=", ">", "<", "> =", "<=", "<>". From these symbols themselves, it should be able to understand its meaning. Here is an example: select CompanyName, City from customer owrated = "london" purpose is to identify all customers in the customer to London. The result is as follows c ompany n ame city ----------------------------------- Around the Horn L ONDO NB's BEVERES L OON NCONSOLIDATED HOLDO NSEASTERN Connection L OON NSEVEN Seas Imports L Ondo N2) Boolean operations. S Q L language Boolean computing includes "A N D", "O R", "N O T", "ie", "or", "Non". The example is as follows, and the order in which companies in the order and the code "V i N e t" are found and processed by employees No. 2. Select ORDERID, CUSTOMERID, Employeeid from ORDERSWHERE CUSTOMERID = "VINET" and EmployeeiD = 2 The result is as follows: o Rder IDC USTOMER ID EmployeeID ------------------------- -------------------------- 1 0 2 9 5 VINET 21 0 7 3 7 Vinet 2 (5) LIKE Operations LIKE operations In the text type of data, find a particular string, plus the use of wildcard, just learn to use the Like operation, you can construct a simple search engine. In the LIKE operation, the following two wildcards are included:% represents multiple characters _ represents a character example as follows: The first example finds "H Ungry" in the customer data table: Select CompanyName, Customerid from Customerswhere CompanyName Like "% Hungry%" results are as follows: c ompany n ame customerid ------------------------------------ ---- -------------------- Hungry Coyote Import Store Hung Chungry Owl All-Night Grocers Hungo Chapter 2 Preparation 57
The second example is to query all the order numbers in the order data table with "1 0 2 4", and a total of five orders. Select ORDERID, CUSTOMERID from ORDERS WHERE ORDERID LIKE "1024_" The result is as follows: o Rder ID Customerid ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ 1 0 2 4 9 TO MS P1 0 2 4 8 VINET (6) IN Operation IN operation The range of values used by a pre-defined value table, when the parameter and the value in the table are considered "true ". For example, in the order data table query all codes for Vinet and TO MSP: Select Customerid, OrderId, ShipName from OrderSwhere Customerid In ("Vinet", "TomSP") The result is as follows: c ustomer IDO Rder IDS Hip N am E- ---------------------------------------------- ---------- To MSP 1 0 2 4 9 Toms Speziit? Tento MSP 1 0 4 3 8 Toms Speziit? Tento MSP 1 0 4 4 6 Toms Speziit? Tento MSP 1 0 5 4 8 Toms spezialit? Tento MSP 1 0 6 0 8 Toms SpeziAlit? Tento MSP 1 0 9 6 7 Toms Speziit? Tenv INET 1 0 2 4 8 VINS et alCools Chevalctor INET 1 0 2 7 4 VINS et alCools Chevalv INET 1 0 2 9 5 VINS et alCools Chevalierv INET 1 0 7 3 7 VINS ET AlCools ChevalierV INET 1 0 7 3 9 VINS et alofts Chevalier (7) BetWeen operations, BetWeen operations are also the range defining the value used, when the parameter and preset value It is only considered "true". However, the way B e t W e e n calculation is not given a value table, but gives a maximum and minimum. When the value in the data table is between this maximum and minimum, it is considered "true" when the maximum and minimum value is included. For example: To find out all the order numbers between 1 0 2 4 9 and 1 0 2 5 4 in the order data table: Select Customerid, ORDERID, ShipName from OrderSwhere ORDERID BETWEEN 10249 and 10254 The results are as follows: 58 Part 1 JSP Getting Started
C uStomer IDO Rder ID ShipName ---------------------------------------------------------------------------------------------------------- ------------------ To MSP 1 0 2 4 9 Toms Speziit? Tenh Anar 1 0 2 5 0 Hanari Carnesv ICTE 1 0 2 5 1 Victuailles En stocks UPRD 1 0 2 5 2 S UP Rêmes Délicesh Anar 1 0 2 5 3 Hanari Carnesc HOPS 1 0 2 5 4 4 CHOP-Suey Chinese Maybe some readers need to get data between maximum and minimum, but does not include maximum and minimum data Then you can do this: Select Customerid, OrderId, ShipName from OrderSwhere ORDERID BETWEEN 10249 and 10254and Not OrderID in (10249, 10254) This result is made: c ustomer IDO Rder IDS Hip N AM E ------- ------------------------------------------------ ---- Hanar 1 0 2 5 0 Hanari Carnesv ICTE 1 0 2 5 1 Victuailles En stocks UPRD 1 0 2 5 2 SUPRêMES Délicesh Anar 1 0 2 5 3 Hanari Carnes (8) Using functions despite most of the relational database system ( RDBMS) has expanded a function that can be used in SQL, and many database systems also allow users to extend their own, but the following functions can always be used: AVG Returns the value in a group removed in this group The number of sum. Count Returns a group of rows or values. MAX returns the maximum value in a set of values. MIN returns the minimum value in a set of values. Here is the actual example: Since the number of all orders: select count (freight) from ORDERS: SELECT AVG (FREIGHT) from ORDERS SELECT MAX (FREIGHT) From Orders find all orders for shipping minimum SELECT MIN (FREIGHT) from Orders (9) Subproof Chapter 2 Preparation Knowledge 59
The concept of subquery is to use the results of a query as the condition of another query. For example, the customer company in the order data table is expressed by the company code, if you need to query the name of the company that is more than 5 0 more than 5 0 Telephone, you need to use sub-query this concept: Select CompanyName, Phone from Customerswhere Customerid in (Select Customerid from OrderSwhere Freight> 500) Results Required Data: C OMPANY N Amephon E ----------- ---------- -------------------------- Ernst Handel 7 6 7 5 - 3 4 2 5Great Lakes Food Market (503) 555-7555 Hungry Owl All-Night Grocers 2967 542Queen Cozinha (11) 555-11 8 9Q Uick - S TOP 0 3 7 2 - 0 3 5 1 8 8255-5939SAVE-A-Lot Markets (208) 555-8097White Clover Markets (206) 555-411 22. Use the data modification command SQL language modification commands including: INSE RT established records. D e l e t e Delete record. U P D at e modify the record. (1) INSERT statement i n s e rt statement has two different formats. It should be noted that the i n s e rt statement assumes that the data table that needs to be inserted into data has been established with the C R e AT E statement or other tools. The first usage is not listed in each column name of the data table, and the data is listed in the order in which the data is established: INSERT INTO CUSTOMERS VALUES ("AAAAA", "Aaaaa Co. Ltd.", "RISO LIAO", "Owner", "Peking University", "Bei Jing", "Beijing", "HaiDian", "100871", "86-10-62754178", "86-10-62763126") The second usage is in the data sheet The back of the data table is listed in the order of the column that needs to be inserted in the following data: Insert Into Customers (Customerid, CompanyName, ContactName, ContactTitle, Address, City, Region, Postalcode, Country, Phone, Fax) Values AAAAA, "Aaaaa Co. Ltd.", "Riso Liao", "Owner", "Peking University", "Bei Jing", "Beijing", "HaiDian", "100871", "86-10-62754178", "86-10-62763126") 60 Part 1 JSP Getting Started
The role of the above two statements is the same, but the second method is recommended in actual use, because the second method can make the columns to be inserted by the data and data, and it is also conducive to inserting null values, for example: now: The company needs to be added to the record quite incomplete, only the company name and code, when using the first method, you need to write SQL statement like this: Insert Into Customers Values ("AAAAA", "AAAAAAAAAAAAAAAAAAAAA CO.LTD.", NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL ") (2) DELETE statement delete statement is quite simple, specific: delete from the table condition where there is not required, when there is no condition, it means that all records in the table are deleted. For example, the statement DELETE FROM customers WHERE CustomerID = "A A A A A" to delete the record just created; the statement DELETE FROM customers to delete all records c u s t o m e r s data sheet. (3) UPDAT E-statement UPD AT E-statement is to update a record domain update in a record in a database, the statement format is as follows: Update Datasheet Set Column Name = New Data Conditions and DELETE statements, the conditions here can also Yes, if there is no condition, then each record in the data table will be updated. Now tell the UPD AT E-statement: First look at the data original: SELECT Customerid, CompanyName from Customers can see the first line record as: c ustomer IDC OMPANY N AM E -------------- -------------------------------- Alfki Alfreds Futterkiste now performs a UPD AT E: Update Customers Set CompanyName = ' Aaaaaa'where Customerid = 'Alfki' Performs the Select Customerid, and the companyName from Customers discovers the result to become: c uSTomer ID CompanyName ---------------- ------- ----------------- Alfkiaaaaa Chapter 2 Preparatory Knowledge 61
In this way, a statement in the database is updated. 2.5 JDBC This section describes JDBC based on the SQL language described in the next section, JDBC enables easy manipulation of the database in the J ava program: from enterprise-level O racle, S Ybase, DB 2 to the simplest A ccess M y sql. In J S P, it is to access the database using J D b C. 2.5.1 What is JD B CJDBC is a Java API for executing a SQL statement, which consists of a set of classes and interfaces written in Java programming languages. JDBC provides a standard A P i for tools / database developers to enable them to write database applications with pure Java APIs. With J D b C, send SQL statements to various relational databases is a very easy thing. In other words, there is a J D b CA P i, you don't have to write a program for accessing the Sybase database, and write another program for accessing the Oracle database, and write another program for accessing the Informix database, and so on. It is enough to write a program with JDBC API, which can send SQL statements to the corresponding database. Moreover, using the application written in Java programming language does not have to worry about writing different applications for different platforms. Combine Java and JDBC will allow programmers to write only a program to run on any platform. Java has rugged, safe, easy to use, easy to understand and automatic features from the network, is an outstanding language to write database applications. The required method is only a method of dialogue between the Java application and various databases. JDBC is a mechanism for such uses. JDBC extends the functionality of Java. For example, using Java and JDBC APIs can publish a web page containing the applet, and the information used by the applet may come from a remote database. Enterprises can also use JDBC to connect all staff to one or more internal databases over Intranet (even if the computers used by these staff include Wi N D O W S, Macintosh, and Unix are different operating systems). As more and more programmers began using Java programming languages, the requirements from Java in conjunction with the database are also increasing. MIS administrators like Java and JDBC combination because it makes information spread easy and economical. Companies can continue to use them to install the database and can easily access information, even if this information is stored on different database management systems. The new program is very short. Installation and version control will be greatly simplified. Programmers can only write only one version or only update once, then put it on the server, and anyone can get the latest version of the application. For business sales information services, Java and JDBC provide an update for external customers to get information. 1. JDBC's use briefly, JDBC can do three things: • Connect to the database. • Send a SQL statement. • process result. The following code segments give the basic examples of the above three steps: Connection Con = DriverManager.getConnection ("JDBC: ODBC: Wombat", "Login", 62 Part 1 JSP Getting Started
"Password"); statement stmt = con.createstatement (); ResultSet RS = Stmt.executeQuery ("SELECT A, B, C from table1"); while (rs.next ()) {int x = rs.Getint (" A "); string s = rs.getstring (" b "); float f = rs.getfloat (" c ");} 2. JDBC is a low-level API, the basic JDBC of the advanced API is a" low "interface, That is, it is used to call the SQL command directly. In this regard, its function is excellent and is easier to use than other database connections, but it is also designed as a foundation interface, and advanced interfaces and tools can be established. The advanced interface is a "user-friendly" interface that uses a more easily understood and more convenient A P i, which is converted to a low-level interface such as JDBC behind the curtain. When writing this article, two JDBC-based advanced A P i is being developed is an embedded S Q L for Java. At least one provider has planned to write it. DBMS implementation S Q: a language specially designed to engage in the database. JDBC requires a SQL statement to pass to the Java method as a string. Instead, the embedded SQL preprocessor allows programmers to use the SQL statement directly with Java. For example, Java variables can be used in SQL statements for accepting or providing SQL values. The embedded SQL preprocessor converts the mixture of this Java / SQL into J V a via JDBC calls. Another relational database table to the Java class direct mapping. Javasoft and other providers have claimed to implement the A P i. In such an "object / relationship" map, each row in the table corresponds to an instance of the class, and the value of each column corresponds to an attribute of the instance. Thus, the programmer can operate directly to the Java object; the SQL call required to access data will be automatically generated in "cover". More complex mappings can also be provided, such as combining rows in multiple tables into a Java class. As people's interest in JDBC is increasing, more and more developers have been using JDBC-based tools to make the program more easily. Programmers have been writing to make the end user's access to the database more simple applications. For example, an application provides a menu that selects a database task. After the task is selected, the application will give prompts and blank to fill in the information required to perform the selected task. After the required information is entered, the application will automatically call the desired SQL command. With the assistance of such a program, even if the user does not understand the syntax of SQL, the database task can also be performed. 3. Comparison of JDBC and ODBC and Other APIs Currently, O D B C (Open Database Connection) API may be the most widely used interface for accessing relational databases. It can connect almost all databases on almost all platforms. Why does Java do not use O D b C? The answer to this question is: Java can use O D B C, but it is best to use the JD B C - O D b C bridge with the help of JDBC, this will be explained later. The problem now has become: "Why do I need J D b C"? The answer is as follows: ODBC is not suitable for use directly in Java because it uses a C language interface. Calling local C code from Java has many shortcomings in security, implementation, robustness, and procedures. Field translation from ODBC C API to Java API is not available.
For example, Java does not have a pointer, while ODBC is widely used (including pointers "void *"). You can imagine JDBC to be converted to the second chapter preparatory knowledge 63
OD B C of the interface, while the object-oriented interface is easier to receive for Java programmers. ODBC is difficult to learn. It is mixed with simple and advanced features, and even for simple queries, its options are also extremely complicated. Instead, JDBC should ensure the simple functionality of simple functions, while the advanced features are allowed when necessary. Enable the "pure Java" mechanism requires a Java API like JDBC. If you use O D B C, you must manually install the ODBC driver manager and driver on each client. If you have written JDBC drivers using Java, JDBC code can be automatically installed, transplanted, and secure security on all Java platforms (from network computers to large machines). In summary, JDBC API is a natural Java interface for basic SQL abstractions and concepts. It is built on the ODBC instead of starting with zero. Therefore, the programmer familiar with ODBC will find that JDBC is easy to use. JDBC retains the basic design characteristics of O D B C; in fact, both interfaces are based on the X / Open SQL CLI (call-level interface). The biggest difference between them is that JDBC is optimized based on Java style and advantages, making it easier to use. Recently, Microsoft introduced new A P i: R d O, ADO, and OLE DB other than ODBC. These designs are the same as JDBC in many ways, ie they are object-oriented database interfaces and are based on classes that can be implemented on ODBC. However, in these interfaces, there is no special feature to make us to turn to replace O D b C, especially in the case of the O D b C driver has established a relatively complete market. Their most is also a decoration in ODBC. This is not to say that JDBC does not need to be developed from its original version; however, most of the new features should be classified into high-grade A P i such as object / relationship maps and embedded SQLs such as the previous section. 4. Two-layer model and three-layer model JDBC API support both two-layer models of database access, and also supports three-layer models. In two layers models, Java Applets or applications will talk directly to the database. This will require a JDBC driver to communicate with the accessed specific database management system. The user's SQL statement is sent to the database, and the result will be sent back to the user. The database can be located on another computer, and the user is connected to the above. This is called client / server configuration, where the user's computer is a client, providing a computer for a server for a server. The network can be i n T R a n e t (which can connect the company staff) or I n t e R n e t. In the three-layer model, the command first is sent to the "intermediate layer" of the service, and then it is sent to the database by it. The database is handled on the SQL statement and send the result back to the intermediate layer, and the intermediate layer is sent back to the user. The MIS administrators found that the three-layer model was very attractive because the intermediate layer can be used to control the types of access and can be updated to the company's data. Another advantage of the intermediate layer is that the user can utilize the easy-to-use advanced A P i, and the intermediate layer will convert it to the corresponding low-level call. Moreover, in many cases the three-layer structure can provide some performance benefits. So far, the intermediate layer is usually written in a C or C language, and these languages are executed faster. However, with the introduction of the optimization compiler (which converts Java byte code to efficient machine-specific machine-specific, the intermediate layer will become increasingly practical. This will be a big progress that allows people to make full use of the advantages of Java (such as rugged, multi-threaded and security). JDBC is very important for accessing the database from the intermediate layer of Java.
5. SQL Consistency Structured Query Language (SQL) is a standard language for accessing the relational database. It is difficult to: Although most D b M s (database management system) use standard S Q Ls for its basic functions, they do not meet the standard SQL syntax or semantics that are recently defined for more advanced features. For example, not all databases support storage programs or external connections, those databases that support this feature are inconsistent. It is desirable that the true standard in SQL can expand
Includes more and more features. But at the same time, the JDBC API must support existing S Q L. One way to solve this problem is to allow any query string to be transferred to the DBMS driver involved. This means that the application can use any more SQL features, but it must take such a risk: it is possible to make an error on some DBMS. In fact, the application query does not even have S Q L, or it can be a dedicated organism (e.g., document or image query) designed for a specific DBMS. The second method of the JDBC handling the SQL consistency problem is to provide an ODBC style essential clause. Syntax provides a standard JDBC syntax for several common SQL disagreements. For example, there is a syntax for the call to date text and stored procedures. For complex applications, JDBC uses a third method to process SQL consistency issues. It utilizes D A T A B A S EmeTadata interface to provide descriptive information about DBMS, so that the application can adapt to each DBMS requirement and function. Since the JDBC API will use the development of advanced database access tools and APIs, it must also pay attention to all of its upper buildings. The "JDBC standard" represents the standard level of the JDBC functionality that the user can rely on. To use this instruction, the driver must at least support ANSI SQL-2 Entry Level (ANSI SQL-2 represents the standards used by the US National Standards Bureau 1 9 9 2). The astry level represents a specific list of SQL features). The driver developer can use the Test Kit with JDBC API to determine if their drivers meet these standards. "JDBC standard" means that the provider's JDBC implementation has passed the consistency test provided by JavaSoft. These consistency tests will check all the classes and methods defined in the JDBC API, and check whether the program has SQL Entry Level feature as much as possible. Of course, these tests are not complete, and JavaSoft currently does not intend to standardize the implementation of each provider. But this consistency definition can indeed provide a certain credibility of JDBC implementation. With more and more database providers, connection providers, Internet providers, and application programmers accepted by JDBC API, JDBC is also rapidly becoming the standard of Java database access. 2.5.2 JDBC products have many available J D b C products available when preparing this article. Of course, the information in this section will soon become outdated information. Therefore, please refer to the JDBC website for the latest information, you can start browsing from the following URL: http: / / java. Sun. COM / Products / JDB C1. Javasoft Framework JavaSoft offers three JDBC product components, they are Java Development Kit (JDK) Component: JDBC Driver Manager, JDBC Driver Test Kit and JDBC-ODBC Bridge. The JDBC driver manager is the pillar of the JDBC architecture. It is actually very small, it is also very simple; its main role is to connect the Java application on the correct JDBC driver and then exit. The JDBC Driver Test Kit provides a certain credibility for the JDBC driver runs your program. Only the driver that passes the package through the JDBC driver is considered to be a JDBC standard TM. The JDBC-ODBC bridge allows the ODBC driver to be used as a JDBC driver. Its implementation provides a way for JDBC's rapid development, and its long-term goal is to provide a way to access certain uncommon DB M s (if you do not implement J D b c) for these uncommon DBMs.
2. JDBC drivers currently known as the JDBC driver can be divided into the following four categories: 1) JDBC-ODBC bridge plus ODBC driver: JavaSoft bridge products provide JDBC access using the ODBC driver. Note that the ODBC binary code (in many cases also includes database client code) is loaded on each client using the driver. Therefore, this type of driver is best suited for enterprise network (this network client installation is not the main issue), or the three-layer structure of the three-layer structure written in Java. 2) Local API - Part of the driver written by Java: This type of driver converts the JDBC calls on the client API to O R A C L E, S Y B A S E, I N f O R ms, DB2, or other DBMS calls. Note that like a bridge driver, this type of driver requires some binary code to each client. 3) JDBC Network Pure Java Driver: This driver converts JDBC to a network protocol that is independent of DBMS, and then this protocol is converted to a DBMS protocol. This network server middleware can connect its pure Java client on a variety of different databases. The specific agreement used depends on the provider. Usually, this is the most flexible JDBC driver. It is possible that all of these solutions provide products suitable for intranet. To make these products support Internet access, they must handle the security aspects of the Web, through the additional requirements of the firewall access. Several providers are adding JDBC drivers to their existing database middleware products. 4) Local protocol pure Java driver: This type of driver converts JDBC calls directly to network protocol used by DBMS. This will allow DBMS servers directly on the client machine to be a very practical solution for Intranet access. Since many such agreements are dedicated, the database provider will be the main source, and several providers have developed such a driver. Finally, we expect that the 3rd, 4 class driver will become the preferred method of accessing the database from the JDBC. The first, 2-class drivers are used as a transition scheme before the direct pure Java driver is not listed. There may be some variations for the first, 2-class drivers (not listed in the table below), which requires a connector, but usually these are more uncomfortable solutions. Class 3, 4-Class drivers provide all the advantages of Java, including automatic installation (for example, by using the APPLET Applet for the J D B C driver to the driver). Table 2 - 3 shows these four types of drivers and their properties: Table 2 - 3 Driver Type Pure J AVA Network Protocol JDBC-OCBC Bridge Non-Direct JDBC Network Based on Local API is required to be based on local The protocol is directly 3. The JDBC driver is obtained. When writing this article, there are already many JDBC drivers that exist. If we use We blogic or We bsphere, the product itself has a lot of database systems drivers. Many important commercial database systems also bring their own J D b C drivers, such as: O R A C L E, S Y B A S E, IBM DB2. To get the latest information about the driver, please review the JDBC website, its URL: http: // java.sun.com/products/jdbc.
2.5.3 Connection Overview Connection object represents the connection to the database. The connection process includes the resulting SQL statement and the result returned on the connection. An application can have one or more connections with a single database, or can be connected to many databases. 1. Open the connection to the database to establish a connection to the database is to call the D R i V e r m a n a g e r.getConnection () method. This method accepts a string containing a URL. The DriverManager class (ie, the so-called JDBC Management) will try to find a driver that can be connected to the database represented by the URL. The DRIVERMANAGER has a list of registered DRIVER classes. When the method getConnection () is called, it will check each driver in the list until a driver that can be connected to the database specified in the URL. Driver's method Connect uses this URL to establish a practical connection. The user can bypass the JDBC management directly call the Driver method. This will be useful in the following special circumstances: When the two drivers can be connected to the database, the user needs to explicitly select the specific drive. But in general, let DRIVERMANAGER class handle open connections will be simpler. The following code shows how to open a connection to a database located at URL "J D B C: O D B C: W O M B A T". The user identifier used is "OBOY", the password is "1 2 J Ava": String Url = "JDBC: ODBC: Wombat"; connection con = drivermanager.getConnection (URL, "OBOY", "12java"); 2. The general usage URL is often confused because the URL is often confused, so the general URL is briefly explained, and then the JDBC URL is discussed. U r l (unified resource locator) provides information required to locate resources on the Internet. You can imagine it as an address. The first part of the URL specifies the protocol used to access the information, which is always following the colon. Commonly used protocols have "F T P" (representing "File Transfer Protocol") and "H T T P" (representing "Hypertext Transfer Protocol"). If the protocol is "F i L E", the resource is indicated on an located on an Internet (the following example is used to represent the part we described; it is not the component of U R L). FTP: / / javasoft. COM / DOCS / JDK - 1 _ APIDOCS. Zi pH Ttp: / / java. Sun. com / products / jdk / c uRrent R ELEAS EF ILE: / HOME / HAROLDW / DOCS / BOOKS / TUTORIAL / Summar y. The remaining part of HTM LURL (behind the colon) gives information about the location of the data resource. If the protocol is F I L E, the remaining part of the URL is the path to the file. For FTP and HTTP protocols, the remaining parts of the URL identify the host and optionally give a more detailed address path. For example, the following is U r L of the JavaSoft home page. This URL only identifies the host: h t t p: / / / j a v a. S u n. C o m starts browsing from the home page, you can go to many other web pages, one of which is the JDBC home page.
The URL of the JDBC home page is more specific. It looks similar to: http: / / java. Sun. COM / Products / JDB C3. JDBC URLJDBC URL provides a method of identifying the database, allowing the corresponding driver to identify the database And establish it with it. In fact, the driver programmer will determine what JDBC URL identifies a particular driver. Users don't have to care about how to form a JDBC URL; they only need to use the URL provided with the drivers used. J D b C
The role is to provide some conventions, and the driver programmer should follow these conventions when constructing their JDBC URL. Since the JDBC URL should be used with a variety of drivers, these agreements should be very flexible. First, they should allow different drivers to use different scenarios to name the database. For example, the ODBC sub protocol allows (but not required) URL contains attribute values. Second, the JDBC URL should allow the driver programmer to be encapsulated in it. This allows you to open a database connection with the applet to a given database dialog, without requiring users to do any system management. Third, the JDBC URL should allow some degree of indirectness. That is, the JDBC URL can point to the logical host or database name, and this logical host or database name will dynamically convert to the actual name by the network naming system. This allows the system administrator without having to declare a particular host as part of the JDBC name. There are a variety of network naming services (such as D N S, NIS, and DCE), and which naming service is not limited. The standard syntax of the JDBC URL is as follows. It consists of three parts, each part is separated by colon: JDBC:
The full syntax is: JDBC: ODBC: [;
Simple SQL statement (without parameters). PrepareStatement method For: SQL statement with one or more IN parameters. A simple SQL statement that is often performed. PrepareCall method is used to call the stored procedure. 7. Transaction transaction consists of one or more such statements: These statements have been executed, complete and submitted or restored. When the method commit or rollback is called, the current transaction ends, and another transaction begins. By default, the new connection will be in automatic submission mode. That is, after the expression is performed, the COMMIT method will be called automatically. In this case, since each statement is submitted separately, a transaction consists only by one statement. If automatic submission mode is disabled, the transaction will wait until the CommT or Rollback method is explicitly invoked, so it will include all the statements that have been executed since the last call commit or rollback method. For the second case, all statements in the transaction will be submitted or restored as a group. Methods Commit makes any changes made by the SQL statement to the database, which will also release all locks held by the transaction. The method ROLLBACK will drop those changes. Sometimes the user does not want this to take effect before another change. This can be achieved by disabling automatic submission and combining two updates in a transaction. If the two updates are successful, call the commit method, so that the two update results become permanent; if one or both updates fails, call the Rollback method to restore the value to be updated. Value. Most JDBC drivers support transactions. In fact, drivers that meet JDBC must support transactions. DatabaseMetadata gives the information given by DBMS. 8. Transaction isolation Level If DBMS supports transaction processing, it must have some way to manage two transactions simultaneously conflict with a database. Users can specify a transaction isolation level to indicate how DBMS should spend more energy to solve potential conflicts. For example, what if the transaction changes a value and the second transaction reads this value before the change is submitted or restored? Suppose the first transaction is restored, the change value read by the second transaction will be invalid, then this conflict can be allowed? The JDBC user can use the following code to indicate that the DBMS allows the value ("DIRTY read") to be read before the value is submitted, where CON is current connection: con.settransactioniSolation; transaction isolation level is higher, to avoid conflict The more energy is also. The Connection interface defines five levels, where the lowest level specifies that the transaction is not supported, and the highest level specifies that any other transaction does not allow any other transaction to make any changes to the data that is being read when the transaction is operated on a database. Typically, the higher the isolation level, the slower the speed of the application execution (for the resource cost of the lock, and the concurrent operation between the user is reduced). When deciding which isolation level, developers must trade between performance requirements and data consistency requirements. Of course, the actual level can be supported depends on the function of the DBMS involved. When creating a Connection object, its transaction isolation level depends on the driver, but is usually the database involved.
Default. Users can change the transaction isolation level by calling the SetisolationLevel method. The new level will take effect within the remainder of the connection process. If you want to change only a transaction isolation level of a transaction, you must set it before the transaction begins, and reset after the end of the transaction. Do not advocate the transaction isolation level to the transaction isolation level, because this will immediately trigger the call to the COMMIT method, so that any changes before this are permanent. 2.5.4 DriverManager Overview The DRIVERMANAGER class is the management of JDBC, which acts between users and drivers. It tracks the available drivers and establishes a connection between the database and the corresponding driver. In addition, the DRIVERMANAGER class also handles transactions such as the display of the driver login time limit and login and tracking messages. For simple applications, general programmers need to use them directly in this class is D R i v E R m a N A g E R. G e TC O N n E C T I O n. As indicated by the name, the method will establish a connection to the database. JDBC allows users to call DriverManager's method g e t D R I v er, GetDrivers, and RegisterDriver and Driver method C O N e c t. But in most cases, let DRIVERMANAGER class management establish the details of the connection. 1. Tracking the Available Driver DriverManager class contains a rigver class that has been registered by calling method D R i v e r m a n a g e r.registerDriver. All DRIVER classes must contain a static part. It creates instances of this class and register the DriverManager class when loading the instance. In this way, the user will not directly call D R I v E R m a n a g e r. R e g i s t e R D R I V E R; but is automatically called by the driver when the driver is loaded. Load the Driver class, then automatically registered in the DriverManager: 1) By calling method C L a s s. F O R n a m e. This will explicitly load the driver class. Since this is not related to external settings, it is recommended to use this method of loading the driver. The following code load class ACME. DB. D River: class.forname ("acme.db.driver"); if you write acme.db.driver to create an instance, and call D River m anage with this example as parameters RR EGISTER D RIVER (this is this), it is in the DriverManager driver list and can be used to create a connection. 2) In the property jdbc.drivers added to the Java.lang.System's properties. This is a list of driver class names loaded by the DriverManager class, separated by a colon. When you initialize the DriverManager class, it searches for system properties J D b C. D R i v e r s, if the user has entered one or more drivers, the DriverManager class will attempt to load them. The following code shows how the programmer enters three driver classes in ~ / .hotjava / Properties (when startup, Hotjava will load it into the system properties list): jdbc.drivers = foo.bah.driver: wombat.sql. Driver: Bad.Test.ourcesDriver; the first call to the DriverManager method will automatically load these driver classes. Note: The second method of loading the driver requires a long-lasting preset environment.
If you can't guarantee this, the call method class.Forname Explicitly loading each driver is more secure. This is also a method of introducing a particular driver because once the DRIVERMANAGER class is initialized, it will no longer check the JDBC.DRIVERS attribute list. In both cases, the newly loaded Driver class is self-registration by calling D R i V E R m a n a g e R.RegisterDriver class. This process will be automatically executed as described above. Due to security, the JDBC management will track which type of loader provides which driver. In this way, when
When the DRIVERMANAGER class opens, it only uses the local file system or the driver provided by the same class loader as the code that issues a connection request. 2. Establish a connection to load the Driver class and register in the DRIVERMANAGER class, which can be used to connect to the database. DRIVERMANAGER will check each driver when the DR.GetConnection method issues a connection request. Sometimes there may be multiple JDBC drivers to connect to a given URL. For example, when connecting to a given remote database, you can use the JDBC-ODBC bridge driver, JDBC to the universal network protocol driver or the driver provided by the database vendor. In this case, the order of the test driver is critical because DriverManager will use the first driver that can be successfully connected to a given URL. First DriverManager is trying to use each driver in the order of registration (the driver listed in JDBC.DRIVERS is always registered first). It will skip the code untrusted drivers unless the source loaded is the same as the source of the code attempting to open the connection. It calls method D RIVE R. Connect on each driver, and passes the user to the URL of the method D River M Anage R.GetConnection to test the driver, and then connect the first one to recognize the URL driver. This method has no efficiency, but since dozens of drivers are not loaded simultaneously, each connection is actually only a few process calls and string comparisons. The following code is an example in which all steps required to connect to the connection with a driver (such as JDBC-ODBC Bridge Driver): Class.Forname ("Sun.jdbc.odbc.jdbCodbcDriver); File: // Load Driver String URL = "JDBC: ODBC: FRED"; DriverManager.getConnection (URL, "UserID", "Passwd"); 2.5.5 A simple example below is a simple example, in this example, will take advantage of JDK The JDBC - ODBC bridge driver queries an example database comes with a Microsoft SQL Server 7.0, and the resulting result is displayed on the screen. 1. Establish O D B C Data Source In the Control Signboard of Wi N D O W S System, select "Data Source (O D B C)", if you use Windows 2000, you will be selected in Administrative Tools. In the system D s n, "Add" is selected, as shown in Figure 2 - 2. Then, create a data source called N ORTHWIND and set the data source as the SQL Server you need, here is assumed to be a local SQL Server data source. If the reader's data source is not locally, please modify itself, as shown in Figure 2 - 3 Indicated. Then, set the default database to N O R t h w i n d in next steps, then click "Finish" to establish O D B C data source, as shown in Figure 2 - 4. 2. After the program code is created, the programming work can be started. The following program is based on a Java Application, using the AW T component to display the result of the database query, the specific program code is relatively simple, the reader should be able Understand.
Import java.awt. *; File: // Before using JDBC, you must introduce Java's SQL package import java.sql. *; Class JDBCTEST EXTENDS frame {textarea mytextarea; public jdbctest () {file: // Setup program Display interface Super ("a simple JDBC Sample"); setLayout (new flowLayout ()); mytextarea = new textarea (30, 80); add (mytextarea); resize (500, 500); show (); mytextArea.AppendText (" Database query, please wait ... / n ");} Void DisplayResults (Resultset Results) throws Sqlexception {file: // First get the query result information ResultSetMetadata ResultsMetAdata = results.getMetadata (); int COLS = ResultsMetadata .getcolumncount (); file: // Waiting for information to clear mytextARE.SETTEXT (""); file: // Display result while (results.next ()) {for (int i = 1; i <= color; i ) {IF (i> 1) MytextArea.AppendText ("/ t"); try {mytextArea.AppendText (Results.getstring (i));} File: // The exception generated when capturing null values Catch (NullPointersExcection E) {} } mytextARE.AppendText ("/ n");}}} public boolean handleevent (EVT.ID == Event.Window_Destroy) {system.exit (0); return true;} return super.handleevent (EVT) } public static void main (string argv []) throws Sqlexception, Exception {file: // Set query string string queryString = "SE Lect * from customers "; jdbctest myjdbctest = new jdbctest (); file: // load driver class.Forname (" Sun.jdbc.odbc.jdbcodbcdriver "); file: // Establish connection connection myconn = drivermanager.getConnection (" JDBC: ODBC: Northwind "," RISO "," RISO ");