[ Pobierz całość w formacie PDF ] .Building a Statement ObjectThe first step in getting data from the MySQL database is to build a Statementobject.The Statement object is designed to be an intermediary between thedatabase connection and the results found from executing some SQL.When a76 Using JDBC with Java Applications and AppletsStatement object executes a query, it returns a ResultSet object.The defaultconfiguration for the Statement object is to return a single ResultSet.If theapplication needs to work with two different results at the same time, multipleStatement objects will need to be instantiated.As you can see from the API doc-umentation in Appendix B Databases and Tables , the Statement object hasquite a few methods associated with it.Throughout this chapter, we cover mostof those methods and how they relate to the MySQL database.The Statement object to be used in our example code is created from the Con-nection object using the method createStatement(), as shown here:Statement statement = connection.createStatement();When calling the createStatement() object, you must enclose it within atry/catch block and capture any SQLException exceptions.The Connectionobject contains three different variations of the createStatement() method: % %Statement createStatement() Instantiates a Statement object to beused for sending queries to the database server. % %Statement createStatement(int resultSetType, int resultSetConcurrency) Instantiates a Statement object to be used for sendingqueries to the database server using the provided type and concurrency. % %Statement createStatement(int resultSetType, int resultSetCon-currency, int resultSetHoldabilitiy) Instantiates a Statement object tobe used for sending queries to the database server using the provided type,concurrency, and holdability.Three parameters are set for ResultSets when a Statement object is created.These are listed below, and we cover them in more detail when we discussResultSet objects: % %ResultSetType The default is TYPE_SCROLL_INSENSITIVE; the possiblevalues areTYPE_FORWARD_ONLY The ResultSet cursor moves forward.TYPE_SCROLL_INSENSITIVE The cursor may scroll in any direc-tion and is not sensitive to changes.TYPE_SCROLL_SENSITIVE The cursor may scroll in any directionand is sensitive to changes. % %ResultSetConcurrency This parameter determines whether the ResultSetmay be updated in place and the updates automatically applied to the data-base.The default is CONCUR_READ_ONLY; it is the only option supportedby Connector/J.Hello World 77 % %ResultSetHoldability This parameter is not implemented in Connector/J simplementation of createStatement().When you re using the createStatement() methods, you include the parameterswhen you re creating a ResultSet or use the defaults as appropriate.In mostcases, you use createStatement() without any parameters.Executing SQLNow that we have a Statement object, it s time to execute the SQL statementsdesigned to return results for use in our application.The Statement objectincludes several types of query methods, as shown in Appendix B.In this sec-tion, we cover the method executeQuery(), which is designed to execute SQLthat will return a result.This means the method expects to execute a SELECTquery.In our example code, the following line sets off the process of retrieving resultsfrom the database:ResultSet rs = statement.executeQuery("SELECT * FROM acc_acc");There are a few things you should note about this code.The first is that the SQLquery statement is provided to the executeQuery() method as a String.Theobject passes the query to the database, which in turn executes it.Connector/Jdoesn t, and shouldn t, make any type of determination on the validity of theSQL being passed by the application.If the database is unable to execute theSQL, a SQLException exception will be thrown.If the command is successful,the executeQuery() method returns a ResultSet object containing the rowsfrom the database.Ultimately, three outcomes can occur when the executeQuery() method exe-cutes.The first is an exception.An exception can occur for many reasons,among them are the following: % %The connection is no longer valid to the database server. % %The SQL has a syntax error in it. % %The currently logged-in user doesn t have permission to the database tableused in the SQL.You need to wrap your executeQuery() in a try/catch block, but it will be adesign issue as to which errors you attempt to recover from and which allowthe application to fail.There are some database operation errors that yourecover from by changing the nature of the operation you might be able toconnect to a secondary database, or limit the results.Other errors may be cata-strophic, like being unable to update the database.The second outcome is aResultSet with results in it.This is the most favorable outcome.The third78 Using JDBC with Java Applications and Appletsoutcome also produces a ResultSet, but instead the set is empty, which indi-cates that the query didn t produce any rows from the database.Displaying ResultsThe example code takes the ResultSet produced by the execution of our querystring and displays the first column of each row.As you see in the next section,the ResultSet object includes a host of methods for manipulating the rows andcolumns it currently stores.Using the ResultSet ObjectThe ResultSet object is the primary storage mechanism for the rows returnedfrom a query on the MySQL database.It is imperative that you have a full under-standing of how the object works and how you get our data out of it.Concep-tually, the ResultSet object looks like an adjustable two-dimensional array, asyou can see in Figure 5.2.acc_id username passwordInternal pointer1034033 jimmy hispassw1034035 jdoe doesFigure 5.2 The ResultSet object.As shown in Figure 5.2, the ResultSet object consists of rows containing databased on the information returned from the database query.The columns of theobject are the fields from the database as specified in the query.If the queryuses a * in the SELECT, then all of the columns from the database will be rep-resented in the ResultSet.If only a few of the columns are listed in the SELECT,then only those columns will appear in the set.The ResultSet uses an internal cursor to keep track of what row data should bereturned when the application requests data.The default behavior for a Result-Set is to maintain read-only data and allow the internal cursor to move forwardthrough the rows.If the data needs to be used a second time, the cursor willneed to be moved to the beginning.When a ResultSet object is first instantiatedand filled, the internal cursor is set to a position just before the first row.A large number of getter methods are available for retrieving data from theResultSet object.These methods pull data from a specific row/column cell andattempt to convert the data to a Java data type as defined by the getter method
[ Pobierz całość w formacie PDF ]
zanotowane.pldoc.pisz.plpdf.pisz.plhanula1950.keep.pl
|