Java 1-contd

956 views

Published on

java

Published in: Education, Technology
0 Comments
0 Likes
Statistics
Notes
  • Be the first to comment

  • Be the first to like this

No Downloads
Views
Total views
956
On SlideShare
0
From Embeds
0
Number of Embeds
17
Actions
Shares
0
Downloads
9
Comments
0
Likes
0
Embeds 0
No embeds

No notes for slide

Java 1-contd

  1. 1. JDBC - 1 JDBC THE JAVA.SQL PACKAGE: The java.sql package contains many classes and interfaces that are used by the JDBC API. These classes and interfaces enable the following basic database functions: creating, opening and managing connections to a database, executing SQL statements, processing the results in the ResultSet, and closing the connection. Some of the Classes and Interfaces of java.sql package are explained below: 1. The DriverManager This class works as an interface between the application (UI) and the Microsoft Access database. It provides the methods for managing database drivers. getConnection(jdbc:odbc:name of DSN, <username>, <password>) This method attempts to establish a connection to the specified database by invoking the JDBC:ODBC bridge and by accepting the name of the DNS as an argument. The system DSN knows where the Access database is. Once a physical connection with a database has been established, we initialize the SQL queries that will be used on the database. ResultSet: The data records retrieved from the database table are held in ResultSet object. Once the table is held in the ResultSet object, the records and the individual fields of each record can be manipulated. The ResultSet contains zero, one or many records. Since this object is created in memory, its contents cannot be seen. To see the data held within the ResultSet object, its each row must be read. We can read each record by using a while loop. The rs.next() method is used in a loop to get one row at a time from the table. 2. Connection Interface: A Connection object represents a connection with a database. SQL statements can be executed and ResultSets are returned from the table. Methods used from Connection interface: a) void close(); The close() method will release the database resources and JDBC resources. b) Statement createStatement(); This method returns a new object that can be used to execute SQL statements. c) void close() - immediately closes the current connection and the JDBC resources it created. Prof. Mukesh N. Tekwani Page 1 of 7
  2. 2. JDBC 3. Statement Interface: A Statement object executes statements and obtains results after their execution. The results are in the form of ResultSet object. Methods used from Statement interface: a) ResultSet executeQuery(String sqlstmt) - This method executes a SQL query that returns a single ResultSet object. b) int executeUpdate(String sqlstmt) - This method executes the SQL UPDATE, DELETE or INSERT statements. It also executes the DDl statements such as CREATE TABLE. It returns a row count or -1 for a statement without an update count. c) int getUpdateCount – It returns the number of rows affected by the previous update statement or -1 if the preceding statement did not have an update count. d) boolean isClosed() – returns true if this statement is closed. 4. PreparedStatement Interface: This interface extends the Statement interface. If a particular SQL statement has to be executed many times, it is precompiled and stored in a PreparedStatement object. This object is then used many times to execute the statement. Methods used from PreparedStatement interface: a) executeQuery() - This method executes prepared SQL query and returns a ResultSet object.. b) executeUpdate() - This method executes the prepared SQL UPDATE, DELETE or INSERT statements. It returns the number of rows affected. For DDL statements such as CREATE TABLE, it returns a 0. c) void setXxx(int n, Xxx x)– sets the value of the nth parameter to x. Xxx is data type. d) void clearParameters() – clears all current parameters in the prepared statement. Example: Consider a query for all books by a publisher, independent of the author. The SQL query is: SELECT Books.Price, Books.Title FROM Books, Publishers WHERE Books.Publisher_Id = Publishers.Publisher_Id AND Publishers.Name = the name from the list box Instead of building a separate query each time the user gives this query, we can prepare a query with a host variable and use it many times, each time filling in a different string for the variable. We can prepare this query as follows: String publisherQuery = “SELECT Books.Price, Books.Title” + “ FROM Books, Publishers” + “ WHERE Books.Publisher_Id = Publishers.Publisher_Id AND Publishers.Name = ?”; Page 2 of 7 mukeshtekwani@hotmail.com
  3. 3. JDBC - 1 PreparedStatement publisherQueryStat = conn.prepareStatement(publisherQuery); Before executing the prepared statement, we must bind the host variables to actual values with a set method. There are different set methods for different data types. To set a string to a publisher name: publisherQueryStat.setString(1, publisher) The first argument is the position number of the host variable that we want to set. The position 1 denotes the first ?. The second argument is the value we want to assign to the host variable. Once the variables have been bound to values, we can execute the query: ResultSet rs = publisherQueryStat.executeQuery() 5. ResultSet Interface: The data generated by the execution of a SQL statement is stored in a ResultSet object.This object can access only one row at a time. This row is called as its current row. When the SQL statement is re-executed, the current recordset is closed and a new RecordSet object is created. Methods used from ResultSet interface: a) void close()- This method is used to release a ResutSet. b) void getString()- This method is used to get the value of a column in the current row. c) next() – A ResultSet is initially positioned before its first row. The first time we call the next() method, it makes the first row as the current row. The second time we call the next() method, the second row becomes the current row, etc d) getXxx(int col no) and getXxx(String collabel) - it returns the value of a column with the given column number or label, converted to the specified type. Here Xxx is a data type such as int, double, String, Date, etc. e) int findColumn(String colname) – gives the column index associated with a column name. f) boolean isClosed() – returns true if this statement is closed. g) boolean first() and boolean last() – moves the cursor to the first or last row. Returns true if the cursor is positioned on a row. h) boolean isFirst() and boolean isLast()– Returns true if the cursor is positioned on first row or last row. 6. ResultSetMetaData Interface: This object is returned by the getMetaData() constructor. It gives information about number of columns, their types and properties or in general about the structure of a database. Methods used from ResultSet interface: a) getColumnCount()- This method returns the number of columns in the ResutSet. b) String getColumnName(int) – This method returns the name of a specific column. c) getTableName() – This method returns the name of a table. Prof. Mukesh N. Tekwani Page 3 of 7
  4. 4. JDBC d) DataBaseMetaData metadt = conn.getMetaData(); DATA SOURCE NAME (DSN) If the original database is created in, say Microsoft Access, then we create a DSN. DSN stands for Data Source Name. A DSN is itself a data structure that contains information about the database, such as, the driver type, the database name, the actual location of the database on the hard disk (i.e., the path), the user name and a password. All this information in DSN is required by ODBC to drivers for creating a connection to the database. DSN is used from an application to send or receive data to the database. DSN is stored in the system registry. GETTING DATA FROM COLUMNS OF A TABLE (ACCESSORS): 1. There are various accessors that permit us to read the contents of a field. 2. Each accessor has two forms, one takes a numeric argument and the other takes a string argument. 3. When we give supply a numeric argument we are referring to the column with that number. E.g., rs.getInt(1)returns the value of the first column. 4. When we supply a string argument we refer to the column in the result set with that name.E.g., rs.getInt("Rollno") returns the value of the column with the name RollNo. 5. The following are the getXXX() methods available to get the column data from the current row: String boolean int float byte double long getString(String columnname); getBoolean (String columnname); getint(String columnname); getfloat(String columnname); getByte(String columnname); getDouble(String columnname); getLong(String columnname); ACCESSING COLUMNS BY COLUMN INDEXES Program : This program demonstrates how we can use the column indexes to identify the columns of the current row. stmt = conn.createStatement( ); ResultSet rs = stmt.executeQuery(“SELECT RollNo, Name, Marks1 FROM TYBSc”); while (rs.next()) { int r = rs.getInt(1); String n = rs.getString(2); Page 4 of 7 mukeshtekwani@hotmail.com
  5. 5. JDBC - 1 int m1 = rs.getInt(3); System.out.print(r + "t"); System.out.print(n + "tt"); System.out.print(m1 + "tt"); } TRANSACTIONS 1. A group of statements form a transaction. 2. A transaction can be committed if all the statements in the group are executed successfully. If one statement in the group fails, the transaction can be rolled back as if none of the statements has been issued. 3. Why should we group statements into a transaction? This is done for maintaining database integrity. E.g., in a banking environment, if money is transferred from one account to another, we must debit one account and simultaneously credit another account. If any one of these transactions cannot be executed the other should also not be executed. Thus, if a debit has taken place but the credit cannot take place, the debit statement should also be disallowed. 4. When statements are grouped in a transaction, then the transaction either succeeds in full and it can be committed or it fails somewhere and the transaction can be rolled back (like undo feature). This rollback will cancel all the updates to the database. 5. By default, a database connection is in autocommit mode. That is each SQL statement is committed to the database as soon as it is executed. Once a statement is committed, you cannot roll it back. We can turn off this default option as follows: conn.setAutoCommit(false) 6. Example: a. Create a Statement object as usual: Statement stat = conn.createStatement(); b. Call executeUpdate() any number of times, as follows: stat.executeUpdate(command1); stat.executeUpdate(command2); stat.executeUpdate(command3); : : c. If all statements have been executed successfully, call the commit method() as foolows: conn.commit(); d. But if any error has occurred, we can call the rollback() command as follws: conn.rollback(); Save Points: We can control the position upto which we want to rollback the commands. This is done by using save points. By creating a save point, we are marking points upto which we can later return without abandoning the entire transaction. Statement stat = conn.createStatement(); //start transaction; rollback goes here Prof. Mukesh N. Tekwani Page 5 of 7
  6. 6. JDBC stat.executeUpdate(command1); Savepoint svpt = conn.setSavePoint(); // set save point, rollback(svpt) will go here stat.executeUpdate(command2); if ( . . . ) conn.rollback(svp); . . . conn.commit(); //undo effect of command 2 If a savepoint is no longer needed, we must release it as follows: conn.releaseSavepoint(svpt); PROGRAMMING EXERCISES 1. Write a JDBC program to create a table GRTGS (Message – Text), insert two greetings into the table, display the table contents, and drop the table. Assume the DSN name is GREETINGS. 2. Use JDBC API to do the following: • Create a table in Oracle with following structure. FriendName Text(20) Dob Date Details Text(20) PhoneNumber Number • Insert the records • Show all the records from the table. 3. Write a program that takes values for BookName and BookId from the user on command prompt and inserts the values in the table Book assuming table to be already created. 4. Write a program that retrieves the records from Book having field Book ,BookName and BookId 5. Write a program that searches for record in table BOOK(BookName varchar2(25),BID number(2,5)) .The value for the BookName is taken from command prompt ,if record found “Record Found” message is displayed and the details regarding the respective Book is displayed else “Record Not Found” is displayed. 6. Write a JDBC program that accepts a table name and displays the total number of records in it. 7. Write a JDBC program that prints the names of all columns in a table that is given on the command line. 8. Write a JDBC program to change the name of a column. Table name is supplied on command line. 9. Create a database “EMPLOYEEDB.MDB” through Microsoft Access. Create a Data Source Name (DSN); give an appropriate name for DSN. Then write a single program to create a table EMPLOYEE (ENO – Integer, ENAME-Text, BPAY-double, ALLOWANCES-double, TAX-double, NETPAYdouble). Through the same program insert 5 records, and display the output in a tabular manner. NETPAY must be calculated and entered in the table using the formula: NETPAY = BPAY + ALLOWANCES – TAX. 10. Write a program that accepts an employee number (ENO) for the above database and if it is found in the table, prints its details, else prints “Record not found”. 11. Modify (alter) the above table (EMPLOYEE) so that it contains one more column called DESIGNATION. Give appropriate SQL query to update this column. Then display all records where designation is “Manager”. Page 6 of 7 mukeshtekwani@hotmail.com
  7. 7. JDBC - 1 REVIEW QUESTIONS 1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11. 12. 13. 14. 15. 16. What are the components of JDBC? Explain the three statement objects in JDBC Explain types of execute methods in JDBC with examples. Explain DriverManager class and its methods. What is DSN? How is it created? Explain steps for connectivity in JDBC Explain any 4 methods of PreparedStatement. Discuss the two-tier architecture for data access. Discuss the three-tier architecture for data access. What are its advantages over the two-tier architecture? Differentiate between Statement and PreparedStatement Explain different methods of ResultSet object. State the object which encapsulates the data retrieved from the database. State the method which is used to to get the value of the specified column of the current row from a database. State the method which is used to get the value of the specified column of the current row from a database. Which method is used to execute a SELECT query? Which method is used to execute DDL statements such as INSERT, UPDATE, and DELETE? Write short notes on: a. JDBC b. JDBC-ODBC Bridge c. Types of driver managers in JDBC d. PreparedStatement e. Transaction and savepoint Explain the following method, and also state the class/interface to which they belong: • next() • close() • forName() • createStatement() • executeUpdate() • prepareStatement() • getConnection() • getString() • getColumnCount() Prof. Mukesh N. Tekwani Page 7 of 7

×