JSP's knowledge summary

xiaoxiao2021-03-06  66

-------------------------------------------------- -------------------- Client (Client) and server-side concept server: Search, server division (hardware server, software server) Hardware Server: Refers to a relative PC, performance and stability, using special hardware computers. Software Server: It is a popular saying that a service software is installed and a machine that provides the corresponding service, we call it a server. Service software has many kinds, common: WWW services software: PWS, IIS, Apachej2ee middleware application server: WebSphere, SilverstreamJSP engine (weak WWW service): Tomcat, Resin, WebLogic, JRunsmtp, POP3: IIS SMTP , Exchange, Lotus DominoftP: IIS comes with the client: Relative to the server, it is a party to enjoy some kind of service, called the client. But if you want some kind of service, you must also install the appropriate software, such as (IE / Netscape, Outlook / Foxmail, CuteftP) ------------------------ --------------------------------------------- Data Type Basic Type There are the following four: int long data types are: Byte (8bits), short (16bits), int (32bits), long (64bits), Float length data types are: single precision (32bits float), double precision (64bits double) The value of the Boolean type variable is: Ture, Falsechar Data types are: Unicode characters, 16-bit Class Type: Integer, Float, Boolean, Character, Double, Short, Byte, Long ---------- -------------------------------------------------- ---------- Conversion Principle: From low precision to high precision Byte, Short, Int, long, float, double, char Note: When two CHAR type operations are automatically converted to INT; when char When computing with other types, it will also be automatically converted to int type, and then other types of automatic conversion basic types are converted to class type.

Positive conversion: By catenio wrapper out of a new class type variable integer a = new integer (2); reverse conversion: convert int b = a.intValue by class wrapper (); ---- -------------------------------------------------- ---------------- Class Type to String Conversion Positive Conversion: Because each class is the subclass of the Object class, and all Object classes have a toString () function Therefore, it can be converted in reverse through the toString () function: a new class type variable eg1: int i = integer.valueof ("123"). INTVALUE () Description: The above case Convert a string into an Integer object, then call the IntValue () method of this object returns its corresponding int value. EG2: float f = float.valueof ("123"). FLOATVALUE () Description: The above example is converting a string into a float object, and then call the FLOATVALUE () method of this object returns its corresponding float value. EG3: Boolean B = Boolean.Valueof ("123"). BooleanValue () Description: The above example is converting a string into a Boolean object, and then call the BooleanValue () method of this object returns its corresponding Boolean value. EG4: DOUBLE D = Double.Valueof ("123"). DoubleValue () Description: The above example is converting a string into a Double object, and then call the DoubleValue () method of this object returns its corresponding Double value. Eg5: long l = long.valueof ("123"). LongValue () Description: The above example is converted a string into a long object, then call the longValue () method of this object returns its corresponding long value. EG6: Char = Character.Valueof ("123"). CHARVALUE () Description: The above example is converting a string into a CHARACTER object, and then call the CHARVALUE () method of this object returns its corresponding char value. -------------------------------------------------- ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- = a ""; reverse conversion: through class wrapper EG1: INT i = integer.parseint ("123") Description: This method can only apply to strings to convert to integer variable EG2: float f = float.valueof "123"). FLOATVALUE () Description: The above example is converting a string into a FLOAT object, and then call the FLOATVALUE () method of this object returns its corresponding float value. EG3: Boolean B = Boolean.Valueof ("123"). BooleanValue () Description: The above example is converting a string into a Boolean object, and then call the BooleanValue () method of this object returns its corresponding Boolean value. EG4: DOUBLE D = Double.Valueof ("123"). DoubleValue () Description: The above example is converting a string into a Double object, and then call the DoubleValue () method of this object returns its corresponding Double value.

Eg5: long l = long.valueof ("123"). LongValue () Description: The above example is converted a string into a long object, then call the longValue () method of this object returns its corresponding long value. EG6: Char = Character.Valueof ("123"). CHARVALUE () Description: The above example is converting a string into a CHARACTER object, and then call the CHARVALUE () method of this object returns its corresponding char value. -------------------------------------------------- ------------- JSP Basic Directive ------ 1 - Script tag declares that the language will be used: <% @. Page language = "java"%> Indicates the JSP instruction, The following script code will use the class in the Java language syntax to reference classes: <% @. Page import = "java.util. *"%> Means that you want to use the class declaration variable in java.util package: <%! Int Count = 0;%> Declare a plastic variable, and assign initial value 0 declaration method: <%! int show (int value) {{return val;}%> Output expression: <% = 2 * x%> Direct output The value of the expression, X must be the previously declared variable (cannot be used), equivalent to the <% =%> JSP comment in ASP: <% - here is comments -%> indicating is a JSP comment At the server side will be ignored, it is not converted to HTML, and it is not seen when the source is viewed. Contains another JSP file: <% jsp: include Page = "Another: JSP"%> Indicates the content of the contents of another file Another.jsp in the current page: <% for (int i = 0, i <10 , i ) // JSP body part Out.println (i "
");%> --------------------------- ----------------------------------------- 2. Instructions --- JSP There are two page instructions (attributes: 6) language properties: <@ page language = "java"%> // Indicates the language import properties used: <@ page import = "java.util. *"% > // Load package Note: In Java, you should load multiple packets, use import separately, and separated by a semicolon; in JSP, if you specify multiple packages with an Import, use a comma. Such as: <% @ page import = "java.util. *, Java.lang. *"%> Can also <% @ Page Import = "java.util. *"%> <% @ Page import = "java.lang * "%>" But does not advocate this, irregular.

) Session attribute: <@ page session = "true or false"%> Default SESSION value true true, <% @ Page session = "true"%> <% IF (session.getvalue ("name") == NULL) Session.putValue ("Name", "123456"); Else Session.putValue ("Name", session.getValue ("name") "1");%> <% out.println (session. GetValue ("name");%> If session = "false", the compile error will occur. ErrorPage Properties: When the current page program is wrong, the program specified by ErrorPage is handled: <@ @ er = "ErrorPage.jsp"%>, Test.jsp: <% @ Page ErrorPage = "ErrorPage.jsp" @ > <%! int i = 0;%> <% = 7 / i%> errorpage.jsp: <% @ page isrrorpage = "true" @> <% = exception%> Run Test.jsp, will be seen 0 except error message. IserrorPage Properties: Indicates whether the current program is an exception handler for another program. Whether it is set, the exception is directed to the current program, and the problem is whether the current program can get this exception. If set to True, an exception of the exception will occur, and you can use it in your code; if false is set, using the Exception program will be erroneous at compile time. Such an error will appear to false, the following error will occur: Error: 500UNABLE TO Compile Class for JSP Write: <% @ Page ISERRPAGE = "True" @> ContentType Property: Specify the type of MIME and JSP files Character encoding method, they all transmit it to the client.

MIME types are: Text / Plain, Text / HTML (Default Type), Text / HTML, Image / GIF, Image / JPEG, Image / JPEG Default Character Coding Method: ISO8859-1 -------- -------------------------------------------------- ---------- Include Directive: Yes to insert a static file to the current page, this file may be an HTML file, a JSP file, or another text file, the format is as follows: <% @ include file = "Include.inc"%>, such as: native.jsp: native file start here.
<% @ include file = "incrude.inc"%> native file end "
Include.inc:include file start here.
<%! String str = "here is include!";%> <% out.pringln (STR "
");%> incrude file end end. < BR> Run native.jsp, the results are as follows: native file start here .include file start! incrude file end end end end end end end end end end end end end end end end end end end. Note: Because the incrude.inc file is inserted when compiling, So only change the content of the incrude.inc file, and do not modify the original JSP page, the result will remain the previous results. (Because the JSP engine judges that the JSP page is not changed, the existing bytecode is directly executed, and the source code is recompiled, so that the modification of Include is not reflected here.) --- -------------------------------------------------- ---- Script JSP script is the code block written in the scripting language specified by the Page Instruction Language Property, which requires the functions completed with JSP mainly. The basics currently used is Java language. The code block must be fully compliant with Java syntax, but can be used with HTML text. In fact, no matter what, it will be converted to servlet, they are the same in servlet.

The: output of the first blank line 5, and then outputs "hello" right: <% for (int i = 0; i <5; i )%>
<%;%> hello
error :( One line of BR; one line hello) =============== <% for (int i = 0; i <5; i )%>
Hello error equivalent: <% For (int i = 0; i <5; i ) {%>
Hello <%}%> ------------------------- -------------------------- Action (<% jsp%>) JSP provides the action instructions provided by: include, Forward, UseBean, GetProperty, SetPropertyInClude The action JSP adds another file to the current page. ------------------------------------------------------------------------------------------------------------------------------------------------------------ ------------------ Forward Action puts the current page to another page, the address seen by the client is the address of the A page, and the actual content is indeed B page content. , here is aa. here is bb. pay attention : Before using Forward, there is no content that has been output to the client, otherwise the exception will occur. -------------------------------------------------- -------------- UseBean action This action is used to generate a bean component and set its ID number and use range action for bean ID = "beanname": Defines the name of generating the BEAN component, cannot be renamed and the value of scope is also the same, otherwise the JSP engine will determine the one you created first. Scope = "Page | Request | Session | Application": Defines the BEAN's activity range, beans can only be used in the range it define, will not access it outside it. JSP is set for it: Page: BE: BEAN's default Using Range REQUEST: A JSP file for any same request until the page is running back to a response or before this, before this. If the redirection, links, etc. are turned to another file.

You can also affect any changes to this bean property in the session cycle by using the Request Object to Access Bean, such as Request.getTribute (BeanName): During the survival period of the entire Session Another page, another Request call to this bean. However, you must specify session = true in the file that created this bean. Application: During the living cycle of the entire Application, any changes to this bean property in the Application cycle will affect this application in this application, another Request, and another session call to this bean. Class = "package.class": A bean according to the class presentation with the class attribute, where the package name must be specified in the class with keyword package. TYPE = "package.class" class = "package.class" type = "package.class" beanname = "{package.class | <% = express%>}" type = "package.class" such as: tt.jsp < JSP: usebean id = "student" scope = "page" class = "mime.student" /> <% = student.getname ()%>
<% student.setname ("WLL");%> student. javapackage mine; public class student {long classno; String name; int age; Boolean sex; public student () {classno = 12345; name = "aaaa"; age = 21; sex = true;} public long getClassno () {return classno;} public void setClassno (long no) {this.classno = no;} public String getName () {return name;} public void setName (String name) {this.name = name;} public int getAge () {return PUBLIC VOID Setage (INT AGE) {this.age = age;} public boolean getsex () {return sex;} public void setsex (boolean sex) {this.sex = sex;}} -------- ------------------------------------------ Note: Scope = "Page" When running Test.jsp files, the initial value of Name is "AAAA". Although reset to "WLL" in the JSP file, the Test.jsp file is run when the "AAAA" Scope = "Session" is still refreshed, and the initial value of Name is "AAAA". Although it is reset to "WLL" in the JSP file, it is still "WLL" after refresh, as long as this window is not closed, any refresh or open a new window, output "WLL". Until all windows are closed, run the Test.jsp file, the output will be "AAAA" for the initial value. When Scope = "Application", run the test.jsp file, the initial value of Name is "AAAA".

Although it is reset to "WLL" in the JSP file, it is still "WLL" after refresh, as long as this window is not closed, any refresh or open a new window, output "WLL". Even if all windows are closed, run the test.jsp file, the output is still "WLL". Unless the service is turned off again, then run the test.jsp file, the output of the Name is the initial value "AAAA". When Scope = "Request", the new one file TEST1.JSP content is the same as Test.jsp. First run the Test.jsp file in your browser, the value of the output Name is the initial value "AAAA". The Test1.jsp file is run in the browser, and the output is "WLL" because they are the same REQUEST.

-------------------------------------------------- ---- GetProperty action: Used to return an attribute value of a BEAN component that has been created: name: The value of the ID when creating the bean component with UseBean Property: Indicates which attribute to get, such as: get the properties of the Student component in the precedent: equivalent: <% = student.classno%> output results: 12345 aaaa 21 ---------------- ----------------------------------------- setProperty action: used to set An attribute value of a BEAN component that has been created: name: Value to create a BEAN component when using UseBean: specify the value: indicate you want to set Attribute name value of the attribute value: for the set properties, such as: Prevent component, attribute set in setProperty < JSP: setProperty name = "student" property = "name" value = "bbb" /> equivalence: <% student.age = 33;%> Output results: 56789 BBBB 33 --------------------------------------- -------------------- Internal object OUT (outputs various data types to the client) Important method : Out.print (Type) or Out.println: Retine Output Out.Newline (): Output a wrap symbol Out.Flush (): Output buffer data out.close (): Turn off output Out.clearbuffer (): Clear the data in the buffer and write the data to the client out.clear (): Clear the data in the buffer, but do not write the data to the client out.getBuffersize (): Get the size of the buffer, The size of the buffer can be used by <% @ page buffer = "size"%> setting Out.getRemaining (): Gets the size of the space that does not use without use. Out.isautoflush (): Return to the Boolean value, if Auto Flush returns true, otherwise Return False.

Whether Auto Fush We can use% @ page is autoflush = "true / false"% to set Note: If the Chinese display problem is directly assigned Chinese string, <% @ page contentType = "text / html; charSet = GB2312"%> It can be displayed normally. But you can't convert the internal code with a getStr (string name) function or a similar function, otherwise Chinese cannot be displayed normally. If the Chinese string passed through the request, you must convert the internal code with a getStr (String Name) function or a similar function, otherwise Chinese cannot be displayed normally. Such as: string aa = Str; Byte [] aa = aa.getbytes ("ISO8859-1"); string bb = new string (aa); different platforms, different server JSP Chinese issues are different, Self-test. -------------------------------------------------- -------------------- Request (information entered by the client) Run: Mainly used to accept the data transmitted to the server side via HTTP protocol connection. Method: getCookies (): Returns the Cookie object of the client, the result is a cookie array getHeader (String name): Get the transfer file header information defined by the HTTP protocol, such as: Request.getHeader ("User-Agent") Return to Client Browser The version number, type getAttribute (String Name): Returns Name specified attribute value, if there is no specified property, return null values ​​(NULL).

GetAttributeNames (): Returns the name of all attributes of the Request object, the result set is an instance of an Enumeration class GetHeadernAmes (): Returns the name of all Request Header, the result set is an Enumeration class instance GetHeaders (String) Name): Returns all values ​​of the Request Header of the specified name, the result set is an Enumeration class instance getMethod (): Getting the client to send data to the server, there is Get, Post, Put, etc. GetParameter (String) Name): Get the client to send the parameter value to the server side, which is specified by Name Get parameternames (): Get all the parameter names to the server side, the result set is an enumeration class instance getParameterValues ​​(String Name): Get the value of the specified parameter get QueryString () get the query string, which transmits getRequesturi (): obtains the client address getServletPath (): Get the client address of the request string by the client. The file path of the script file setttribute (String Name, java.lang.Object O): Set the name of the name to name, which is specified by the Object Type of o GetServerName (): Get the name GetServerPort (): get The port number of the server getRemoteAddr (): Get the client's IP address getRemotehost (): Get the name of the client computer, if it fails, return to the client computer's IP address getProtocol (): Get the client to transfer data to the server. Agreement name, such as http / 1.1 --------------------------------------------- ------------------------ Application: Once you are created, you will keep Application.setttribute ("Name) unless the server is turned off unless the server is turned off. ", VAL) Request.setttribute (" Name ", VAL) method: GetAttribute (String Name): Returns the value of the Application object attribute specified by name This is an Object object GetAttributeNames (): Returns the name of all Application object properties, the result set is an instance of an Enumeration class GetItParameter (String Name): Returns the initial value of the Application Planted Properties, this property is specified GetServerInfo (): Get the information of the current version servlet compiler setttribute (String Name, Object Object): Initialize an attribute with Object, this property is specified by name ----------------- -------------------------------------------------- --- Response (Control HTTP Connection) Role: Send data to the client, such as cookie, HTTP file information, etc.

Method: AddCookie (cookie cookie): Add 1 cookie object to save the client's user information. This cookie is available in a getCookies () method to get this cookie, such as: <% cookie mycookie = new cookie ("uname", "wsr"); response.addcookie; cookie delmyCookie = New cookie ("MyCookie", NULL; DelmyCookie .SetMaxage (0); DelmyCookie .SetPath (/ "); response.addcookie (DELMYCOOKIE);%> addheader (String name, string value): Add HTTP file header, the header will pass to the client, if the same name Header exists, the original header will be overwritten: String Name: Determine whether the HTTP file header of the specified name exists and returns the Boolean Senderror (INT SC): Error message to the client, such as: 505: server internal error; 404 : The web page cannot be found, such as: response.Senderror (response.sc_no_content); setHeader (String Name, String Value): Set the value of the HTTP file header of the specified name, if this value exists, it will be covered by the new value such as 1: Let the web page all 5 seconds, "Refresh", "5");%> the current dateis: <% = new date ()%>, such as 2: Setting the HTTP header using the Response object <% respternse.setContentType ("Application / PDF"); Response.setHeader ("Content-Disposition", "Attachment; FileName = /" Syntax.pdf / ");%> Sendredirect (" Error.html ") //// Redirect function --------------------------------------------- -------------------------- Exception (processing exceptions and errors) Role: Handling all the errors and exceptions that occur during execution. There are 3 Method. Note: You must use the Exception object GE without <% @ page isrrorpage = "true"%> TMESSAGE (): Return Error Message PRINTSTACKTRACE (): Output an error and error in the form of a standard error (): Returns 1 for exceptions in the form of a string ----------- -------------------------------------------------- ------------- Session (save user information) Run: Save each user's information session.putValue ("name", val) session.getValue ("name") Note: SESSION The information saved and retrieved cannot be the basic data type, but must be the corresponding Object object of Java.

Method: GetAttribute (String Name): Get the properties of the specified name, if the property does not exist, return nulltattributenames (): Returns the first attribute object stored in the Session object, the result set is an instance of an Enumeration class getCreationTime (): Returns the time created by the session object, from January 1, 1970, getId from January 1, 1970: The server will give it a number that will not be repeated, this method returns the number of the current session GetLastAccessedTime. : Returns the time of the current session object last once, returning from the milliseconds of the Since January 1, 1970, getMaxinActiveInterval (): Get the survival time of the session object Removeattribute (String Name): Delete the specified property (including attributes Name, attribute value) SetAttribute (String name, java.lang.object value): Set the attribute value of the specified name, and store it in the session object ---------------- -------------------------------------------------- --------- Using the Java Bean Component: Yes, you can reuse anywhere in the application, other components, documents, Web sites, and applications can be reused in multiple scenarios. JavaBean concept JavaBean is an application interface independent of platform and structure, which itself can ignore internal structures and detail issues, just define their external features and external functions. -------------------------------------------------- -------------------------- it has three interfaces to develop separately, which is: attributes, methods, and event JavaBeans attribute JSP components There are two attributes: single value attribute, index properties single-value properties: equivalent to a member variable defined in the usual programming, which can only have a data value, this data value can be any data type in Java, including Class and interface. Such as: int counter; Float Tax; String name; DateTime; Note: A special single-value property (Boolean properties), only two allowed values: true, false index properties: equivalent to array, when When you store a batch of data, you need to use index properties. Such as: int ID []; string name []; float score []; --------------------------------- ----------------------------- JavaBean method methods include constructor and access methods. Construction method: similar to the constructor in the class (ie, initialize it and its member variable), its method is the same as the class of this JavaBean.

Such as: Package Student; Public class student {int counter; ind id []; string name []; float score []; boolean whiszkid; public student () {id = new int [50]; name = new String [50] Score = new float [50]; counter = 0;}} ----------------------------------- ----------------------------------------- Access method: is defined in the component Attribute access, including reading and writing (general situation is similar to the method defined and used in Java), pay attention to its name rules: read an attribute: getxxx () override an attribute: setXXX () Access single value properties: For example, the two access methods can be: read attribute values: public int getCounter {Return counter;} rewrite attribute value: public void setcounter (int counter) {this.counter = Counter;} Access Boolean single-value attributes: Use the ISXXX () method for the read attribute value, such as the above-mentioned Boolean attribute whiz: public boolean iswhizkid () {return whizkid;} Access index properties: Sometimes it is necessary to define a few An access method, but their name rules are still the same, such as the name properties of the above, it needs to be defined in this reading and rewriting method: read an attribute value in the index property: public string getname (int index) { Return Name [index];} Read all attribute values ​​in the index properties: public string [] getName () {return name;} Rewinding an attribute value in the index property: public void setname (int index, string str) {name [index] = Str;} All attribute values ​​in index properties: public void setname (String [] str) {name = str ;;} ---------------------------------------------------------------------------------------------------------------------- -------------------------------------------------- - Creating a BEA written in JSP in JSP n, actually creates an object of such a class. -------------------------------------------------- -------------------- The work of the client is divided into two parts: First, send a request to the server to send a submission to the server side, in the customer End check, as well as the finishing of the page ------------------------------------- ------------------------------ Client submission method client submission method is divided into two: GET and POST Submit Get The information passed is only about 2kb, and it is a ciode transmission information, and all the information can be seen in the address bar. POST can deliver a lot of information, encrypted transmission, all information can be invisible in the address bar.

POST Submit all POST submission can only be generated in the form: Direct submission (Submit submission), indirect submission (Submit) 1) Direct Submit: Click the Submit button, immediately submit

Note: Submit button has a default event, is to submit Note: Before submission, first return a warning box" Hello "on the screen, if return is true, then the page is submitted; if return is false, the page does not submit. 2) Indirect Submit: means that the click button itself cannot be submitted, and only the submission can be completed by scripts, called indirect submission. Note: At the onclick, you can also be onMousedown, onmouseup, etc. Button is just a normal button, it does not have submission, only After the script specified by ONClick can complete the commit button, execute the function triggered by the onclick event, if the return value is true, otherwise it will be submitted. GET Submit Get Submit Procedure in Form Form and URL 1) 2 generated in Form Added in Form> Enter the URL address in the address bar in all URLs, followed by Parameters http://*.asp? Name = www & agn = 20 On the hyperlink "frame src =" * .asp? Name = www "Name = Frame Name" in the frame name> in the ASP redirect statement "* .asp? Name = WWW "in the client object document: Document.Location =" http: // * .asp? name = www "in the client object Window: WINDOW.Open (" http: // * .asp? name = www ") ------------------------------------ -------------------------- The method of obtaining the client information is done by the Request object.

The information submitted to the server side is divided into three categories: the first category: client information (including client IP address, port number, host name, submission, etc.) Second category: submitted to the server side by form or URL Information Issue 3: Cookie Information ----------------------------------------------------------------------------------------------------------------------------------------------------------- -------------------------------- get the first type of information: Request.getHeader ("User-Agent") Returns The version number of the client browser, Type GetHeader (String Name): Get the transfer file header information defined by the HTTP protocol, request. GetMethod (): Get the client to transfer data to the server, there is Get, Post, Put, etc. Request getRequesturi (): Get the client address request. getServletPath (): obtain the file path of the script file requested by the client request. getServerName (): Get the server's name request.getServerPort (): get the server Port number request.getRemoteAddr (): Get the client's IP address request.getRemoteHost (): Get the name of the client computer, if it fails, return to the client computer's IP address request.getProtocol (): request.getHeadernAmes (): Return All Request Header's name, the result set is an instance of an Enumeration class. Request.getHeaders (String Name): Returns all values ​​of the Request Header of the specified name, the result set is an enumeration instance - -------------------------------------------------- ---------------------------- Get the second class GET information: request. GetQueryString ("Variable name or control name") get the query String, the string is transferred to the server by the client in a GET method ----------------------------------- ---------------------------------------------- get the second Class POST information: request.getparame Ter (String Name): Get the parameter value of the client to the server side, which specifies the name request.getParameterNames (): obtains all the parameter names to the server side, the result set is an enumeration class Instance Request.getParameterValues ​​(String Name): Get value worth of specified parameters ------------------------------------------------------------------------------------------------------------------------------ -------------------------------------------------- ------ get a third class cookie information: Request.getCookies: Return to the client's cookie object, the result is a cookie array ------------- -------------------------------------------------- ------------------ Database Primary Section For everyone convenient, use Access as an example step:

In the "Start" - "Control Panel" - "Management Tool" - "Data Source (ODBC)" - "System DSN" - "Add" - "Select Data Source Driver" - "Complete" - "ODBC installation fills in the data source, click 'OK'" - "Complete". The five elements of the database connection: IP address port number (port number is fundamentally fixed, unless specifically set) means that the corresponding database driver selection database account, password (is assigned to the database) SQL The statement (Send via the Statement object) JDBC principle JDBC is a connection between Java and data. Because the ODBC is written in the C language, communication with C language programs in Java is more difficult, so interface technologies for Java programs and database connections are generated by Java language. JDBC and database connection JDBC is connected to a specific database, which is automatically loaded directly through classes in the JDBC API class library. This library is typically in the Java.sql package, which contain classes for implementing other functions connected to the database, including connecting to the database, transmitting queries, and accepting query results. Detailed introduction of the following four classes: Role: Connection to the database Send SQL statement processing results Connection CN = DriverManager.getConnection ("JDBC: ODBC: Wombat", "Login", "Password"); statement stmt = cn.createstatement ); // Send SQL statement 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");} // processing result ------------------------------------------------------------------------------ ---------------------------------------- DRIVERMANAGER CYY This class is used to load drive Program, all of its members are static members, so they do not need to instantiate it in the program, and they can access it directly through class names. The DriverManager class is the management of JDBC, which acts on the user and driver loading driver Class.Forname ("Company Name. Database Name. Driver Name), such as: Class.Forname (" Sun.jdbc.odbc.jdbCodbDriver) Establish a connection to load the Driver class and register after the DriverManager class can be used to connect to the database. When the calling driver.manager.getConnection () issues a connection request, DriverManager checks each driver to see if it can establish a connection.

Method: Connection getConnection (String URL, String User, String Password) where user and password are the user and password of the login database, the first parameter is pointing to the URL of the database, its format is as follows: JDBC: (Subprotocol) :( Subname) Subprotocol : Sub protocol, specify how database or what to connect to the database Subname: Establish a connection, can be a data source name, or point to an online database such as: The following is a usual driver (JDBC-ODBC bridge driver) ), And even a student data source, an anonymous login example: class.forname ("Sun.jdbc.jdbcodbcDriver"); // Loading the driver string url = "jdbc: odbc: student"; connection CN = DriverManager.getConnection (URL, "Anonymous", "); getConnection (): Returns a connection class object. If successful, this object points to a connection to this database; otherwise, this object will be an empty NullConnection class Connection class to point to the same database. Role: Manage the connection to the database, such as sending queries to the database and receiving query results of the database are based on it; turn off this connection after all tasks with the connection of the database. Method: Statement CreateStatment (): New Statement object, this object can send query information to the database (): Close the connection with the database and release the occupied JDBC resource boolean isclose (): Judgment is still working with the database connection Statement : Statement object is used to send SQL statements to the database. After creating a Statement object After the connection to a specific database, you can send a SQL statement with this connection. The Statement object creates CreateStatement with the Connection method. Connection CN = DriverManager.getConnection (RUL, "Sunny", "); statement stmt = cn.createStatement (); In order to execute a statement object, the SQL statement sent to the database will be supplied to statement as a parameter ResultSet RS = Stmt.executeQuery ("SELECT A, B, C from Table2"; Using the Statement object Execute Statement interface provides three ways to execute SQL statements ExecuteQuery (): The statement used to generate a single result set, such as: SELECT statement ExecuteUpdate (): Used to perform INSERT, UPDATE, or DELETE, statement, etc. The statement statement completed statements in the two combinations, that is, it is considered to be completed. For an ExecuteQuery () method returns a result set, the statement is completed when all rows of the ResultSet object are retrieved. For method executeUpdate (), when it is executed, when the statement is executed, when a few call executers (), only after retrieving all result sets or the update count it generates, the Statement object Statement object will be automatically automatically automatically shut down.


New Post(0)