JDBC – Insert Records ”; Previous Next This chapter provides examples on how to insert a record, insert multiple records, insert with select query in a table using JDBC application. Before executing following example, make sure you have the following in place − To execute the following example you can replace the username and password with your actual user name and password. Your MySQL or whatever database you are using is up and running. Required Steps The following steps are required to create a new Database using JDBC application − Import the packages − Requires that you include the packages containing the JDBC classes needed for database programming. Most often, using import java.sql.* will suffice. Register the JDBC driver − Requires that you initialize a driver so you can open a communications channel with the database. Open a connection − Requires using the DriverManager.getConnection() method to create a Connection object, which represents a physical connection with a database server. Execute a query − Requires using an object of type Statement for building and submitting an SQL statement to insert records into a table. Clean up the environment try with resources automatically closes the resources. Example: Inserting Record in a Table In this example, we”ve three static strings containing a dababase connection url, username, password. Now using DriverManager.getConnection() method, we”ve prepared a database connection. Once connection is prepared, we”ve prepared a Statement object using createStatement() method. As next step, We”ve prepared a SQL string to insert a record into a table REGISTRATION and inserted the record in database by calling statement.executeUpdate() method. Thereafter we”ve updated the SQL string to insert more new records and using executeUpdate() method, all records are inserted one by one. In case of any exception while connecting to the database, a catch block handled SQLException and printed the stack trace. Copy and paste the following example in JDBCExample.java, compile and run as follows − import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import java.sql.Statement; public class JDBCExample { static final String DB_URL = “jdbc:mysql://localhost/TUTORIALSPOINT”; static final String USER = “guest”; static final String PASS = “guest123”; public static void main(String[] args) { // Open a connection try(Connection conn = DriverManager.getConnection(DB_URL, USER, PASS); Statement stmt = conn.createStatement(); ) { // Execute a query System.out.println(“Inserting records into the table…”); String sql = “INSERT INTO Registration VALUES (100, ”Zara”, ”Ali”, 18)”; stmt.executeUpdate(sql); sql = “INSERT INTO Registration VALUES (101, ”Mahnaz”, ”Fatma”, 25)”; stmt.executeUpdate(sql); sql = “INSERT INTO Registration VALUES (102, ”Zaid”, ”Khan”, 30)”; stmt.executeUpdate(sql); sql = “INSERT INTO Registration VALUES(103, ”Sumit”, ”Mittal”, 28)”; stmt.executeUpdate(sql); System.out.println(“Inserted records into the table…”); } catch (SQLException e) { e.printStackTrace(); } } } Now let us compile the above example as follows − C:>javac JDBCExample.java C:> When you run JDBCExample, it produces the following result − C:>java JDBCExample Inserting records into the table… Inserted records into the table… C:> Example: Inserting Record in Single Statement in a Table In this example, we”ve three static strings containing a dababase connection url, username, password. Now using DriverManager.getConnection() method, we”ve prepared a database connection. Once connection is prepared, we”ve prepared a Statement object using createStatement() method. As next step, We”ve prepared a SQL string to insert multiple records in one go into a table sampledb4 and inserted the record in database by calling statement.execute() method. Thereafter we”ve run a select query to read all records from the table and printed the same. In case of any exception while connecting to the database, a catch block handled SQLException and printed the stack trace. Copy and paste the following example in JDBCExample.java, compile and run as follows − import java.sql.*; // This class demonstrates use of multiple inserts within a single SQL public class JDBCExample { static final String DB_URL = “jdbc:mysql://localhost/TUTORIALSPOINT”; static final String USER = “root”; static final String PASS = “guest123”; public static void main(String args[]) { try{ Connection conn = DriverManager.getConnection(DB_URL, USER, PASS); Statement stmt = conn.createStatement(); stmt.execute(“INSERT INTO sampledb4(id, name) VALUES(3, ”Sachin”), (4, ”Kishore”)”); System.out.println(“—– Successfully inserted into table sampledb4 —-nn”); System.out.println(“Displaying records from sampledb4 table, showing inserted values”); System.out.println(“—————————“); ResultSet rs = stmt.executeQuery(“select * from sampledb4”); while(rs.next()){ System.out.println(“id: ” + rs.getInt(1)); System.out.println(“name: ” + rs.getString(2)); } }catch(SQLException e){ e.printStackTrace(); } } } Now let us compile the above example as follows − C:>javac JDBCExample.java C:> When you run JDBCExample, it produces the following result − C:>java JDBCExample —– Successfully inserted into table sampledb4 —- Displaying records from sampledb4 table, showing inserted values ————————— id: 3 name: Sachin id: 4 name: Kishore C:> Example: Inserting Record Using Select Statement in a Table In this example, we”ve three static strings containing a dababase connection url, username, password. Now using DriverManager.getConnection() method, we”ve prepared a database connection. Once connection is prepared, we”ve prepared a Statement object using createStatement() method. As next step, We”ve prepared a SQL string to insert records using a select query into a table sampledb4 and inserted the record in database by calling statement.execute() method. Thereafter we”ve run a select query to read all records from the table and printed the same. In case of any exception while connecting to the database, a catch block handled SQLException and printed the stack trace. Copy and paste the following example in JDBCExample.java, compile and run as follows − import java.sql.*; // This class demonstrates use of INSERT..SELECT SQL, //where data is inserted in table using select from another table. public class JDBCExample { static final String DB_URL = “jdbc:mysql://localhost/TUTORIALSPOINT”; static final String USER = “root”; static final String PASS = “guest123”; public static void main(String args[]) { try{ Connection conn = DriverManager.getConnection(DB_URL, USER, PASS); Statement stmt = conn.createStatement(); // Data from students
Category: jdbc
JDBC – Transactions
JDBC – Transactions ”; Previous Next If your JDBC Connection is in auto-commit mode, which it is by default, then every SQL statement is committed to the database upon its completion. That may be fine for simple applications, but there are three reasons why you may want to turn off the auto-commit and manage your own transactions − To increase performance. To maintain the integrity of business processes. To use distributed transactions. Transactions enable you to control if, and when, changes are applied to the database. It treats a single SQL statement or a group of SQL statements as one logical unit, and if any statement fails, the whole transaction fails. To enable manual- transaction support instead of the auto-commit mode that the JDBC driver uses by default, use the Connection object”s setAutoCommit() method. If you pass a boolean false to setAutoCommit( ), you turn off auto-commit. You can pass a boolean true to turn it back on again. For example, if you have a Connection object named conn, code the following to turn off auto-commit − conn.setAutoCommit(false); Commit & Rollback Once you are done with your changes and you want to commit the changes then call commit() method on connection object as follows − conn.commit( ); Otherwise, to roll back updates to the database made using the Connection named conn, use the following code − conn.rollback( ); The following example illustrates the use of a commit and rollback object − try{ //Assume a valid connection object conn conn.setAutoCommit(false); Statement stmt = conn.createStatement(); String SQL = “INSERT INTO Employees ” + “VALUES (106, 20, ”Rita”, ”Tez”)”; stmt.executeUpdate(SQL); //Submit a malformed SQL statement that breaks String SQL = “INSERTED IN Employees ” + “VALUES (107, 22, ”Sita”, ”Singh”)”; stmt.executeUpdate(SQL); // If there is no error. conn.commit(); }catch(SQLException se){ // If there is any error. conn.rollback(); } In this case, none of the above INSERT statement would success and everything would be rolled back. For a better understanding, let us study the Commit & Rollback – Example Code. Using Savepoints The new JDBC 3.0 Savepoint interface gives you the additional transactional control. Most modern DBMS, support savepoints within their environments such as Oracle”s PL/SQL. When you set a savepoint you define a logical rollback point within a transaction. If an error occurs past a savepoint, you can use the rollback method to undo either all the changes or only the changes made after the savepoint. The Connection object has two new methods that help you manage savepoints − setSavepoint(String savepointName) − Defines a new savepoint. It also returns a Savepoint object. releaseSavepoint(Savepoint savepointName) − Deletes a savepoint. Notice that it requires a Savepoint object as a parameter. This object is usually a savepoint generated by the setSavepoint() method. There is one rollback (String savepointName) method, which rolls back work to the specified savepoint. The following example illustrates the use of a Savepoint object − try{ //Assume a valid connection object conn conn.setAutoCommit(false); Statement stmt = conn.createStatement(); //set a Savepoint Savepoint savepoint1 = conn.setSavepoint(“Savepoint1”); String SQL = “INSERT INTO Employees ” + “VALUES (106, 20, ”Rita”, ”Tez”)”; stmt.executeUpdate(SQL); //Submit a malformed SQL statement that breaks String SQL = “INSERTED IN Employees ” + “VALUES (107, 22, ”Sita”, ”Tez”)”; stmt.executeUpdate(SQL); // If there is no error, commit the changes. conn.commit(); }catch(SQLException se){ // If there is any error. conn.rollback(savepoint1); } In this case, none of the above INSERT statement would success and everything would be rolled back. For a better understanding, let us study the Savepoints – Example Code. Print Page Previous Next Advertisements ”;
Useful – Java Tutorials
Java Tutorial Table of content What is Java? Java First Example Online Java Compiler Java Features Java Applications Java Jobs & Opportunities Why to Learn Java? Who Should Learn Java Prerequisites to Learn Java Java Online Quizzes Java Examples Getting Started Java Practices Java References Java Certification Java FAQs Job Search PDF Version Quick Guide Resources Discussion Java Tutorial This Java tutorial has been written for beginners to advanced programmers who are striving to learn Java Programming. We have provided numerious practical examples to explain the concepts in simple and easy steps. This tutorial has been prepared and reviewed by experienced Java Programmers at Tutorials Point and best effort has been put to make it useful for the students and Java developers. After completing this tutorial, you will find yourself at a moderate level of expertise in Java Programming, from where you can elevate yourself to the next levels. What is Java? Java is a popular high-level, object-oriented programming language, which was originally developed by Sun Microsystems and released in 1995. Currently, Java is owned by Oracle and more than 3 billion devices run Java. Java runs on a variety of platforms, such as Windows, Mac OS, and the various versions of UNIX. Today Java is being used to develop numerous types of software applications including Desktop Apps, Mobile apps, Web apps, Games, and much more. Java is a general-purpose programming language intended to let programmers Write Once, Run Anywhere (WORA). This means that compiled Java code can run on all platforms that support Java without the need to recompile. In this tutorial, you will learn everything about Java starting from basics to advanced concepts such as overview, history, installations, basic input/output, conditional & control statements, arrays, classes, inheritances, method overloading & overriding, exceptional handling, exception handling, and many more. Java First Example The first example in Java is to print “Hello, World!” on the screen. Let”s have a quick look at the first examples in Java programming example.: public class MyFirstJavaProgram { /* This is my first java program. * This will print ”Hello, World!” as the output */ public static void main(String []args) { System.out.println(“Hello, World!”); // prints Hello, World! } } Online Java Compiler Our Java programming tutorial provides various examples to explain the concepts. To compile and execute the given Java programming examples in your browser itself, we have provided Online Java Compiler. You can Edit and Execute almost all the examples directly from your browser without the need to set up your development environment. Try to click the icon to run the following Java code to print conventional “Hello, World!” using Java Programming. Below code box allows you to change the value of the code. So, please try to change the value inside println() and run it again to verify the result. public class MyFirstJavaProgram { /* This is my first java program. * This will print ”Hello, World!” as the output */ public static void main(String []args) { System.out.println(“Hello, World!”); // prints Hello, World! } } Java Features Java is a feature-rich language. Java is evolving continuously with every update and updates are coming after every six months. Following are some of the main features of Java language – Object Oriented: Java is a pure object-oriented language and everything in Java is an object. Java supports OOPS principles like Inheritance, Encapsulation, Polymorphism, Classes , and so on. Java itself can be extended as well being based on an object model. Platform Independent: Java code is platform independent. A Java code is not compiled into machine-specific code, it is compiled into a platform-neutral byte code. This byte code is executed by JVM which runs the code on the underlying platform. This capability makes Java a Write Once Run Anywhere language. Easy To Learn: Java inherits features from C, and C++ and developers can easily learn Java if they know any of the C or C++ language. Even for someone new to computer languages, java is very easy to learn from scratch. Secure: Java is secure by architecture. A developer is not required to directly interact with underlying memory or Operating System. Java provides automatic garbage collection so developers are not required to worry about memory leaks, management, etc. Architectural-Neutral: Java byte code can be executed on any kind of processor. JRE automatically handles the code execution on different types of processors. Portable – A Java code written on a windows machine can be executed without any code change on MacOS and vice versa. There is no need to make any operating system-specific code changes. Robust – Java is a very robust language with very strong compile-time error checks, strict type checking, and runtime exception handling. Multithreading – Java provides inbuilt support for multiprocessing and multithreading. Java provides thread handling, monitors, deadlock handling, racing conditions, etc. High Performance – Java although being interpreted, still is very performant. JIT (Just In Time) compiler helps in improving performance. Distributed – Java is designed for distributed systems and is the most popular language for developing internet-based applications as the internet is a distributed environment. Java Applications Since Java supports object-oriented features and is platform-independent, it is extensively used in various fields. Listed below are a few areas where Java is used – Enterprise solutions Game development Secured web development Embedded systems Mobile application development Big Data Applications, and many more. Java Jobs & Opportunities Java is very high in demand and all the major companies are recruiting Java Programmers to develop their Desktop, Web and Mobile applications. Today a Java Programmer with 3-5 years of experience is asking for around $120,000 annual package and this is the most demanding programming language in America. Though it can vary depending on the location of the Job. Following are the great companies who are using Java and they need good Java Programmers: Google Microsoft Facebook IBM Amazon Netflix Pinterest Uber JetBrains Many more… So, you could be the next potential employee for any of these major companies. We
JDBC – Connections
JDBC – Database Connections ”; Previous Next After you”ve installed the appropriate driver, it is time to establish a database connection using JDBC. The programming involved to establish a JDBC connection is fairly simple. Here are these simple four steps − Import JDBC Packages − Add import statements to your Java program to import required classes in your Java code. Register JDBC Driver − This step causes the JVM to load the desired driver implementation into memory so it can fulfill your JDBC requests. Database URL Formulation − This is to create a properly formatted address that points to the database to which you wish to connect. Create Connection Object − Finally, code a call to the DriverManager object”s getConnection( ) method to establish actual database connection. Import JDBC Packages The Import statements tell the Java compiler where to find the classes you reference in your code and are placed at the very beginning of your source code. To use the standard JDBC package, which allows you to select, insert, update, and delete data in SQL tables, add the following imports to your source code − import java.sql.* ; // for standard JDBC programs import java.math.* ; // for BigDecimal and BigInteger support Register JDBC Driver You must register the driver in your program before you use it. Registering the driver is the process by which the Oracle driver”s class file is loaded into the memory, so it can be utilized as an implementation of the JDBC interfaces. You need to do this registration only once in your program. You can register a driver in one of two ways. Approach I – Class.forName() The most common approach to register a driver is to use Java”s Class.forName() method, to dynamically load the driver”s class file into memory, which automatically registers it. This method is preferable because it allows you to make the driver registration configurable and portable. The following example uses Class.forName( ) to register the Oracle driver − try { Class.forName(“oracle.jdbc.driver.OracleDriver”); } catch(ClassNotFoundException ex) { System.out.println(“Error: unable to load driver class!”); System.exit(1); } You can use getInstance() method to work around noncompliant JVMs, but then you”ll have to code for two extra Exceptions as follows − try { Class.forName(“oracle.jdbc.driver.OracleDriver”).newInstance(); } catch(ClassNotFoundException ex) { System.out.println(“Error: unable to load driver class!”); System.exit(1); catch(IllegalAccessException ex) { System.out.println(“Error: access problem while loading!”); System.exit(2); catch(InstantiationException ex) { System.out.println(“Error: unable to instantiate driver!”); System.exit(3); } Approach II – DriverManager.registerDriver() The second approach you can use to register a driver, is to use the static DriverManager.registerDriver() method. You should use the registerDriver() method if you are using a non-JDK compliant JVM, such as the one provided by Microsoft. The following example uses registerDriver() to register the Oracle driver − try { Driver myDriver = new oracle.jdbc.driver.OracleDriver(); DriverManager.registerDriver( myDriver ); } catch(ClassNotFoundException ex) { System.out.println(“Error: unable to load driver class!”); System.exit(1); } Database URL Formulation After you”ve loaded the driver, you can establish a connection using the DriverManager.getConnection() method. For easy reference, let me list the three overloaded DriverManager.getConnection() methods − getConnection(String url) getConnection(String url, Properties prop) getConnection(String url, String user, String password) Here each form requires a database URL. A database URL is an address that points to your database. Formulating a database URL is where most of the problems associated with establishing a connection occurs. Following table lists down the popular JDBC driver names and database URL. RDBMS JDBC driver name URL format MySQL com.mysql.jdbc.Driver jdbc:mysql://hostname/databaseName ORACLE oracle.jdbc.driver.OracleDriver jdbc:oracle:thin:@hostname:port Number:databaseName DB2 COM.ibm.db2.jdbc.net.DB2Driver jdbc:db2:hostname:port Number/databaseName Sybase com.sybase.jdbc.SybDriver jdbc:sybase:Tds:hostname: port Number/databaseName All the highlighted part in URL format is static and you need to change only the remaining part as per your database setup. Create Connection Object We have listed down three forms of DriverManager.getConnection() method to create a connection object. Using a Database URL with a username and password The most commonly used form of getConnection() requires you to pass a database URL, a username, and a password − Assuming you are using Oracle”s thin driver, you”ll specify a host:port:databaseName value for the database portion of the URL. If you have a host at TCP/IP address 192.0.0.1 with a host name of amrood, and your Oracle listener is configured to listen on port 1521, and your database name is EMP, then complete database URL would be − jdbc:oracle:thin:@amrood:1521:EMP Now you have to call getConnection() method with appropriate username and password to get a Connection object as follows − String URL = “jdbc:oracle:thin:@amrood:1521:EMP”; String USER = “username”; String PASS = “password” Connection conn = DriverManager.getConnection(URL, USER, PASS); Using Only a Database URL A second form of the DriverManager.getConnection( ) method requires only a database URL − DriverManager.getConnection(String url); However, in this case, the database URL includes the username and password and has the following general form − jdbc:oracle:driver:username/password@database So, the above connection can be created as follows − String URL = “jdbc:oracle:thin:username/password@amrood:1521:EMP”; Connection conn = DriverManager.getConnection(URL); Using a Database URL and a Properties Object A third form of the DriverManager.getConnection( ) method requires a database URL and a Properties object − DriverManager.getConnection(String url, Properties info); A Properties object holds a set of keyword-value pairs. It is used to pass driver properties to the driver during a call to the getConnection() method. To make the same connection made by the previous examples, use the following code − import java.util.*; String URL = “jdbc:oracle:thin:@amrood:1521:EMP”; Properties info = new Properties( ); info.put( “user”, “username” ); info.put( “password”,
JDBC – Introduction
JDBC – Introduction ”; Previous Next What is JDBC? JDBC stands for Java Database Connectivity, which is a standard Java API for database-independent connectivity between the Java programming language and a wide range of databases. The JDBC library includes APIs for each of the tasks mentioned below that are commonly associated with database usage. Making a connection to a database. Creating SQL or MySQL statements. Executing SQL or MySQL queries in the database. Viewing & Modifying the resulting records. Fundamentally, JDBC is a specification that provides a complete set of interfaces that allows for portable access to an underlying database. Java can be used to write different types of executables, such as − Java Applications Java Applets Java Servlets Java ServerPages (JSPs) Enterprise JavaBeans (EJBs). All of these different executables are able to use a JDBC driver to access a database, and take advantage of the stored data. JDBC provides the same capabilities as ODBC, allowing Java programs to contain database-independent code. Pre-Requisite Before moving further, you need to have a good understanding of the following two subjects − Core JAVA Programming SQL or MySQL Database JDBC Architecture The JDBC API supports both two-tier and three-tier processing models for database access but in general, JDBC Architecture consists of two layers − JDBC API − This provides the application-to-JDBC Manager connection. JDBC Driver API − This supports the JDBC Manager-to-Driver Connection. The JDBC API uses a driver manager and database-specific drivers to provide transparent connectivity to heterogeneous databases. The JDBC driver manager ensures that the correct driver is used to access each data source. The driver manager is capable of supporting multiple concurrent drivers connected to multiple heterogeneous databases. Following is the architectural diagram, which shows the location of the driver manager with respect to the JDBC drivers and the Java application − Common JDBC Components The JDBC API provides the following interfaces and classes − DriverManager − This class manages a list of database drivers. Matches connection requests from the java application with the proper database driver using communication sub protocol. The first driver that recognizes a certain subprotocol under JDBC will be used to establish a database Connection. Driver − This interface handles the communications with the database server. You will interact directly with Driver objects very rarely. Instead, you use DriverManager objects, which manages objects of this type. It also abstracts the details associated with working with Driver objects. Connection − This interface with all methods for contacting a database. The connection object represents communication context, i.e., all communication with database is through connection object only. Statement − You use objects created from this interface to submit the SQL statements to the database. Some derived interfaces accept parameters in addition to executing stored procedures. ResultSet − These objects hold data retrieved from a database after you execute an SQL query using Statement objects. It acts as an iterator to allow you to move through its data. SQLException − This class handles any errors that occur in a database application. The JDBC 4.0 Packages The java.sql and javax.sql are the primary packages for JDBC 4.0. This is the latest JDBC version at the time of writing this tutorial. It offers the main classes for interacting with your data sources. The new features in these packages include changes in the following areas − Automatic database driver loading. Exception handling improvements. Enhanced BLOB/CLOB functionality. Connection and statement interface enhancements. National character set support. SQL ROWID access. SQL 2003 XML data type support. Annotations. Print Page Previous Next Advertisements ”;
JDBC – Result Sets
JDBC – Result Sets ”; Previous Next The SQL statements that read data from a database query, return the data in a result set. The SELECT statement is the standard way to select rows from a database and view them in a result set. The java.sql.ResultSet interface represents the result set of a database query. A ResultSet object maintains a cursor that points to the current row in the result set. The term “result set” refers to the row and column data contained in a ResultSet object. The methods of the ResultSet interface can be broken down into three categories − Navigational methods − Used to move the cursor around. Get methods − Used to view the data in the columns of the current row being pointed by the cursor. Update methods − Used to update the data in the columns of the current row. The updates can then be updated in the underlying database as well. The cursor is movable based on the properties of the ResultSet. These properties are designated when the corresponding Statement that generates the ResultSet is created. JDBC provides the following connection methods to create statements with desired ResultSet − createStatement(int RSType, int RSConcurrency); prepareStatement(String SQL, int RSType, int RSConcurrency); prepareCall(String sql, int RSType, int RSConcurrency); The first argument indicates the type of a ResultSet object and the second argument is one of two ResultSet constants for specifying whether a result set is read-only or updatable. Type of ResultSet The possible RSType are given below. If you do not specify any ResultSet type, you will automatically get one that is TYPE_FORWARD_ONLY. Type Description ResultSet.TYPE_FORWARD_ONLY The cursor can only move forward in the result set. ResultSet.TYPE_SCROLL_INSENSITIVE The cursor can scroll forward and backward, and the result set is not sensitive to changes made by others to the database that occur after the result set was created. ResultSet.TYPE_SCROLL_SENSITIVE. The cursor can scroll forward and backward, and the result set is sensitive to changes made by others to the database that occur after the result set was created. Concurrency of ResultSet The possible RSConcurrency are given below. If you do not specify any Concurrency type, you will automatically get one that is CONCUR_READ_ONLY. Concurrency Description ResultSet.CONCUR_READ_ONLY Creates a read-only result set. This is the default ResultSet.CONCUR_UPDATABLE Creates an updateable result set. All our examples written so far can be written as follows, which initializes a Statement object to create a forward-only, read only ResultSet object − try { Statement stmt = conn.createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY); } catch(Exception ex) { …. } finally { …. } Navigating a Result Set There are several methods in the ResultSet interface that involve moving the cursor, including − S.N. Methods & Description 1 public void beforeFirst() throws SQLException Moves the cursor just before the first row. 2 public void afterLast() throws SQLException Moves the cursor just after the last row. 3 public boolean first() throws SQLException Moves the cursor to the first row. 4 public void last() throws SQLException Moves the cursor to the last row. 5 public boolean absolute(int row) throws SQLException Moves the cursor to the specified row. 6 public boolean relative(int row) throws SQLException Moves the cursor the given number of rows forward or backward, from where it is currently pointing. 7 public boolean previous() throws SQLException Moves the cursor to the previous row. This method returns false if the previous row is off the result set. 8 public boolean next() throws SQLException Moves the cursor to the next row. This method returns false if there are no more rows in the result set. 9 public int getRow() throws SQLException Returns the row number that the cursor is pointing to. 10 public void moveToInsertRow() throws SQLException Moves the cursor to a special row in the result set that can be used to insert a new row into the database. The current cursor location is remembered. 11 public void moveToCurrentRow() throws SQLException Moves the cursor back to the current row if the cursor is currently at the insert row; otherwise, this method does nothing For a better understanding, let us study Navigate – Example Code. Viewing a Result Set The ResultSet interface contains dozens of methods for getting the data of the current row. There is a get method for each of the possible data types, and each get method has two versions − One that takes in a column name. One that takes in a column index. For example, if the column you are interested in viewing contains an int, you need to use one of the getInt() methods of ResultSet − S.N. Methods & Description 1 public int getInt(String columnName) throws SQLException Returns the int in the current row in the column named columnName. 2 public int getInt(int columnIndex) throws SQLException Returns the int in the current row in the specified column index. The column index starts at 1, meaning the first column of a row is 1, the second column of a row is 2, and so on. Similarly, there are get methods in the ResultSet interface for each
JDBC Tutorial
JDBC Tutorial PDF Version Quick Guide Resources Job Search Discussion What is JDBC? JDBC API is a Java API that can access any kind of tabular data, especially data stored in a Relational Database. JDBC works with Java on a variety of platforms, such as Windows, Mac OS, and the various versions of UNIX. Why to Learn JDBC? JDBC stands for Java Database Connectivity, which is a standard Java API for database-independent connectivity between the Java programming language and a wide range of databases. The JDBC library includes APIs for each of the tasks mentioned below that are commonly associated with database usage. Making a connection to a database. Creating SQL or MySQL statements. Executing SQL or MySQL queries in the database. Viewing & Modifying the resulting records. Applications of JDBC Fundamentally, JDBC is a specification that provides a complete set of interfaces that allows for portable access to an underlying database. Java can be used to write different types of executables, such as − Java Applications Java Applets Java Servlets Java ServerPages (JSPs) Enterprise JavaBeans (EJBs). All of these different executables are able to use a JDBC driver to access a database, and take advantage of the stored data. JDBC provides the same capabilities as ODBC, allowing Java programs to contain database-independent code. The JDBC 4.0 Packages The java.sql and javax.sql are the primary packages for JDBC 4.0. This is the latest JDBC version at the time of writing this tutorial. It offers the main classes for interacting with your data sources. The new features in these packages include changes in the following areas − Automatic database driver loading. Exception handling improvements. Enhanced BLOB/CLOB functionality. Connection and statement interface enhancements. National character set support. SQL ROWID access. SQL 2003 XML data type support. Annotations. Interfaces and Classes of JDBC API Following is the list of mostly used interfaces and classes in JDBC API. DriverManager class − used to load a SQL driver to connect to database. Connection interface − used to make a connection to the database using database connection string and credentials. Statement interface − used to make a query to the database. PreparedStatement interface − used for a query with placeholder values. CallableStatement interface − used to called stored procedure or functions in database. ResultSet interface − represents the query results obtained from the database. ResultSetMetaData interface − represents the metadata of the result set. BLOB class − represents binary data stored in BLOB format in database table. CLOB class − represents text data like XML stored in database table Types of API in JDBC JDBC driver implementations vary because of the wide variety of operating systems and hardware platforms in which Java operates. Sun has divided the implementation types into four categories, Types 1, 2, 3, and 4, which is explained below − Type 1 − a JDBC bridge is used to access ODBC drivers installed on each client machine. For example, JDBC-ODBC Bridge driver in JDK 1.2. Type 2 − JDBC API calls are converted into native C/C++ API calls, which are unique to the database. These APIs are vendor specific and vendor provided driver is required to be installed. It is also called JDBC Native API. For example, Oracle Call Interface (OCI) driver. Type 3 − A three-tier approach is used to access databases. The JDBC clients use standard network sockets to communicate with a middleware application server. The socket information is then translated by the middleware application server into the call format required by the DBMS, and forwarded to the database server. It is also called JDBC-Net Pure Java driver. Type 4 − A pure Java-based driver communicates directly with the vendor”s database through socket connection. This is the highest performance driver available for the database and is usually provided by the vendor itself. For example, MySQL”s Connector/J driver to connect to MySQL database. Audience This tutorial is designed for Java programmers who would like to understand the JDBC framework in detail along with its architecture and actual usage. Prerequisites Before proceeding with this tutorial, you should have a good understanding of Java programming language. As you are going to deal with RDBMS, you should have prior exposure to SQL and Database concepts. Print Page Previous Next Advertisements ”;