JDBC foundation

xiaoxiao2021-03-31  204

Come, we know! JDBC, Java platform connectivity. What does it mean? What does it mean? It is the "tool" on the Java platform and the database. Still first review the interface: from bottom to, interface It is an abstraction of "Case", which is abstracted by a case. In turn, from top down, the abstract interface is a commitment and constraint for the case. That is, as long as you implement the interface I specified Your class has already had an interface to the external promise. As long as the "customer" will operate the interface, you don't need to re-learn, you will implement the new class of the interface! Ok, use it, you can use the interface. Realize the same behavior of the unrelated class. 2. You can specify how many classes need to be implemented via the interface. 3. You can understand the interaction method of the object without the need to understand the class blue. These sentences are very clear. Let's have a book that has a book to write this paragraph with more than 30 pages. As a result, someone else is not as good as I understand, but I understand why some people want to write a book. I understand it. The above things, JDBC is well understood. In order to universal, Java requires a mechanism to operate the same method when operating different manufacturers database, rather than every contact of a database, to learn new methods. Complete this "Things" of the mechanism is called "JDBC". Simple points, JDBC has two parts, JDBC API and JDBC Driver Interface. JDBC API is provided to "customers" (that is, I am like you, my rookie programmer If it is a master written a JDBC, a group of a group of databases is independent of the database's API, and the operation of any database can be done with this set of APIs. So to translate these general APIs into a specific database. The "Directive" is to be implemented by JDBC Driver Interface, so this part is a programming interface for JDBC driver developers, which translates us to their own databases through the JDBC API to the database. It is still to take a look at how JDBC works. Because the JDBC API is a general interface, how do the program know which database I want to connect? So first load (or register available Driver when connecting to the database ), In fact, JDBC signature. Load drivers and a lot of methods, the most commonly used, first dissolve the driver class into memory, as a "current" driver. Note "Current" means that there are multiple drivers in memory, But only the currently loaded drivers as the preferred link. Class.Forname ("Org.gjt.mm.mysql. Driver "); Class.Forname method is the DRIVER class that is soluble in memory in memory. DRIVER class, the Driver class corresponds to the corresponding type of implementation to the JDBC API interface. For example Org.gjt.mm.mysql.connection instance object assigns a java.sql.connection interface handle so that "customers" can call the actual org.gjt.mm.mysql.connection by operating the java.sql.connection handle. Method. It is if it is mapped, this is a manufacturer programming, "customer" as long as Class.Forname ("Org.gjt.mm.mysql.driver); method can operate successfully JDBC API. One Ordinary The database connection process is: 1. Load the driver. 2. DRIVERMANAGER to get a handle with the database. 3. Bind the statement to be executed by connecting the handle. 4. Receive the execution result. 5. Optional pair results Processing. 6. The necessary closures and database links.

==============================================

As mentioned earlier, the registration driver has a multi-method, class.Forname (); is an explicit load. After a driver class is loaded by ClassLoad, DriverManager will register this driver class. This call is automatically called, that is, the drivermanager.registerdriver () method is called automatically, (reflective mechanism ??) Of course, we can also call DriverManager.RegisterDriver () to register the driver, but in my experience. The applet is not successful when calling this method in the browse of MS, that is, the MS is invalid to the implementation of the JVM built-in in the browser. In addition, we can also use the system properties jdbc.drivers to load multiple drivers: System.SetProperty ("JDBC.DRIVERS", "Driver1: Driver2: .....: DRIVERN"); multiple drivers are separated from ":", so JDBC will search in sequential when connecting The first driver that can successfully connect the specified URL. In the basic article, we will not introduce these advanced features. After successful registration drivers, we can use DriverManager's static method getConnection to get a reference to the database: Connection conn = drivermanager.getConnection (URL); if the link is successful, return Connection object conn, if you are NULL or throw an exception, the explanation is not set up with the database. There are three overloads for the getConnection () method. One is the simplest source that gives only the data source is: getConnection (URL), the other is to give some data source information, Tenconnection (URL, Properties), and another is to give a data source, username, and password: GetConnection (URL, User, Passwod), for data source information. If we want to give more information when connecting, you can press this information into a Properties, of course, you can directly press the username password, you can still press Some other information such as specified character sets, encoding methods, or default operations. After getting a link, there is a channel with the database to find the channel. We can do what we want. Or first introduce some general Operation: If we want to operate on the database in the database, you must first bind a statement: Statement Stmt = Conn.createStatement (); then use this statement to perform actions. Fundamental operations, you can have two result returns, if the execution query operation, return to the result set ResultSet, if the update operation is performed, return the record record Note, SQL operation strictly distinguish between only two, one is to read operation (query operation), the other is write operation (update operation), so Create, Insert, Update, Drop, Delete, etc. The operation of the behavior is an update operation. ResultSet RS = Stmt.executeQuery ("Select * from table where xxxxx"); int x = stmt.executeUpdate ("delete from table where ...);

If you have to use ExecuteQuery to execute an update operation, but don't give it to a handle, of course, a slight experienced programmer will do this. As for the processing of the result set, we are discussed in the next section Because it is an Operable option, only the query operation returns the result set, for the completion of the operation process, a very necessary step is to turn off the database link, before you don't know more JDBC knowledge, you first This step is the most important step in JDBC operation. I will continue to remind you to turn off the database link !!!!!!!!!!! A completed example is in the steps introduced above. Such: (Note, in order to press the above steps, this example is not the best) try {class.forname ("org.gjt.mm.mysql.driver);} catch (exception e) {system.out. Println ("No successful loading driver:" E.TOString ()); return;} // For experience like me, you can directly determine the abnormal cause from E.TOSTRING (). / If you are a novice, you should pick it a subclass, how do you know which exception to capture? A simple // method is to pick up TRY {}, directly class.Forname ("Org.gjt.mm. MySQL.Driver ");, ed // translator will tell you which exception is you caught, of course, this is a way to fracture, it is best to / / to see the JDK document, it will tell you What exceptions have to be captured. Connection conn = null; try {conn = drivermanager.getConnection ("JDBC: MySQL: // Host: 3306 / MySQL", "User", "passwd"); statement stmt = conn. CreateStatement (); ResultSet RS = Stmt.executeQuery ("Select * from table"); // RS processing [rs.close ();] [stmt.close ();]} catch (exception e) {system.out.println ("Database operation is exception:" E.TOSTRING ());} finally {Try {conn.close ();} catch Exception) {}} // No matter how you learn about how to operate about the database process, if you believe me, start from now, // Please write the code close to the FINALLY block, cut! =========================================

As mentioned earlier, the Statement object is used to bind the operations to be performed, and there are three execution methods on it: 用 to execute the executEcuteQuery () used to perform update operations () and use to perform dynamics Unknown operation of Execute (). JDBC does not detect the SQL statement to be executed when compiling, just looks a string, only if the driver executes the SQL statement, know the correct or not. A Statement object can only There is a result set in activities. This is tolerance, that is, even if there is no CLOSE () method that calls the Resultset () method, simply open the closure of the previous result set. So if you want to be simultaneous Multiple result set operations, you have to create multiple Statement objects. If you don't need to operate simultaneously, you can operate multiple result sets on a Statement object. Here I have to explain it, many people will use a statement. Nested inquiry, then ask me to say why can't you loop? The truth is clear. Let's analyze the nested query: connection conn = null; statement stmt = null; conn = ....... STMT = Conm.createStatement (xxxxxx); ResultSet RS = Stmt.executeQuery (SQL1); while (rs.next ()) {str = rs.getstring (xxxxx); ResultSet RS1 = Stmt.executeQuery ("SELECT * FROM Table Where Field = STR ");} When stmt.executeQuery (" Select * FROM Table WHERE Field = Str "); When assigned to RS1, the implied operation is that the RS is closed, can you still loop? So if To operate multiple result sets, you must let it bind to different Statement objects. Good in a Connection object, you can create any number of Statement objects without having to reagent. About gaining and setting the Statement option: Just look at its getxxx method and setXXX method, you only take the following: setQueryTimeout, set a SQL execution timeout limit. Setm AxRows, set the result set of rows. SteeScaProcessing, if the parameter is true, the driver is replaced by sending the SQL statement to the database, otherwise letting the database handles yourself, of course these default values ​​can be queried by GET method Two Subcaters: PreparedStatement: For multiple executions of the same statement, STATEMENT will send the SQL statement to the database each time, this efficiency is not high, and if the database supports pre-transmissions, PreparedStatement can be implemented first The statement is sent once, then each execution without having to send the same statement, the efficiency is of course improved, of course, if the database does not support precompile, PREPAREDStatement works like Statement, just the efficiency is not high without the need for user skiller intervention. In addition PreparedStatement also supports reception parameters. As long as you transfer different parameters after the precompile, it can be implemented. PreparedState ps = conn.prepareStatement ("SELECT * FROM Table WHEREE field =?"); Ps.setstring (1, parameters ResultSet RS = ps.executeQuery (); CallableStatement: is a subclass of PreparedStatement, which is only used to perform stored procedures. Callablestatement sc = conn.preparecall ("{call query ()});

ResultSet RS = cs.executeQuery (); ======================================

As the last part of the basic knowledge, let's take the results of the result set, of course, the processing of the general result set. As for the multi-result set returned by the stored procedure, we are still introduced in advanced applications. SQL statement how to execute It is a query action, then return a resultSet object, if you want to display the query results to the user, you must process the resultSet .ResultSet returns to a list of qualified records in a table, to process the results of the ResultSet And for the processing of the columns of each row, it can be in any order (note that this is only the requirements of the JDBC specification, and some JDBC implementations are still required to handle the user in order, but this is a very small number). In fact, Although you can press any order while you can process columns, if you press from left to right, you can get a high performance. From the underlying, you will find the ResultSet object, in any of the books of the JDBC, you are Will not get such knowledge, because that is a database manufacturer. The ARESULTSET object is actually maintained a two-dimensional pointer, the first dimension is to the current line, and the first line it points to the first line of the result set, so if To access the first line, you must first need next (), you must first update next () before you can access, then the second dimension pointer points to the column, as long as you go to gtxxx (column), only Connection Go to the database to take the real data, otherwise there is no machine to really put the data you want to take in memory. So, I have to remember that if the connection is already closed, it is impossible to get it again. Data. There are many people asking me, I can't get a resultset to write it into the session and close the connection, so don't join each time. I can only tell you, your thoughts are very good, but Error! Of course, Cacherow and Webcacherow can cook and WebCacherow in Javax.sql package, but that is nothing out of the RESULTSET's row of RESULTSET, and there is no different value to the RESULTSET's row. The columns in the row can be accessed by field name or index. Below is a simple search result: ResultSet RS = Stmt.executeQuery ("SELECT A1, A2, A3 from Table"); while (rs.next )) {INT i = rs.getinT (1); string a = rs.getstring ("a2"); .............. } For the result set used to display, using the next () is the most common, if next () returns false, the description has not been available. But sometimes we may not even have a line, and if there is a record I don't know how many lines, then if you have to do different processing and no records, you should use the following process: if (rs.next ()) {// Because NexT () is already DO {= = rs.getinT (1); String a = rs.getstring ("a2");} ESL = System.out.Println ("No Conditional Record!");} Type Conversion: The getxxx method of the ResultSet will strive to convert the SQL data type in the result set to Java data type, and most types can be converted. But there are still many confused, if you can't convert a SQL's float into Java Date, you can't "" we "

转载请注明原文地址:https://www.9cbs.com/read-130976.html

New Post(0)