|
|
|
|
Working with Java Database Connectivity Assume that ABC Ltd is an automobile sales part manufacturing company that has many branches across the world. The corporate office at New York maintains MSAccess database for the sales details of various products, stock with each branch, personnel details etc. The New Delhi office wants to establish connection with this remote database via Java Applet and sends in the above data to the corporate office. The solution for the above issues lies with JDBC or Java Database Connectivity. Before proceeding further, let us take a quick view regarding Microsoft's ODBC and the preference of JDBC over ODBC.Microsoft ODBC API offers connectivity to almost all databases on almost all platforms and is the most widely used Programming interface for accessing relational databases. But ODBC cannot be used directly with Java Programs due to various reasons described below.
Hence, JDBC came into existence. If you had done Database Programming with Visual Basic, then you will be familiar with ODBC. You can connect a VB Application to MSAccess Database or an Oracle Table directly via ODBC. Since Java is a product of Sun Microsystems, you have to make use of JDBC with ODBC in order to develop Java Database Applications. Steps required to implement a Java Database Program Connection conn = DriverManager.getConnection("jdbc:odbc:<DSN NAME>"); Here note that getConnection() is a static method, meaning it should be accessed along with the class associated with the method. The DSN Name is the name which you gave in the Control Panel while registering the Database or Table. STEP 3: Creating JDBC Statements Statement stmt = conn.createStatement(); STEP 4: Executing the Statement ResultSet rs = stmt.executeQuery("select * from student"); If you want to select only the name field you have to issue a SQL Syntax like Select Name from Student The executeUpdate() method is called whenever there is a delete or an update operation. STEP 5: Looping through the ResultSet The ResultSet object contains rows of data that is parsed using the next() method like rs.next(). We use the getXXX method of the appropriate type to retrieve the value in each field.If the first field in each row of ResultSet is Name (Stores String value), then getString method is used. Similarly, if the Second field in each row stores int type, then getInt() method is used like: System.out.println(rs.getInt("ID")); STEP 6: Closing the Connection and Statement ObjectsAfter performing all the above steps, you have to close the Connection and RecordSet Objects appropriately by calling the close() method. For example, in our above code we will close the object as conn.close() and statement object as stmt.close()
|
|
||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||