Simple Tutorial For Using JDBC - UMD

3y ago
52 Views
2 Downloads
310.45 KB
8 Pages
Last View : 29d ago
Last Download : 3m ago
Upload by : Angela Sonnier
Transcription

Simple tutorial for using JDBCThe JDBC ( Java Database Connectivity) API defines interfaces and classes for writing databaseapplications in Java by making database connections. Using JDBC you can send SQL, PL/SQLstatements to almost any relational database. JDBC is a Java API for executing SQL statements andsupports basic SQL functionality. It provides RDBMS access by allowing you to embed SQL insideJava code. Because Java can run on a thin client, applets embedded in Web pages can containdownloadable JDBC code to enable remote database access. You will learn how to create a table,insert values into it, query the table, retrieve results, and update the table with the help of a JDBCProgram example.Although JDBC was designed specifically to provide a Java interface to relational databases, you mayfind that you need to write Java code to access non-relational databases as well.JDBC ArchitectureJava application calls the JDBC library. JDBC loads a driver which talks to the databaseIn general, to process any SQL statement with JDBC, you follow these steps:①②③④⑤Establishing a connection.Create a statement.Execute the query.Process the ResultSet object.Close the connection.1. Configuring a JDBC development environmentFirst of all, you should download the JDBC Driver for your DBMS. For this class, you can use“ojdbc6.jar” provided on class web-site. The ojdbc6.jar is a JDBC driver for Oracle Database 11g.The below web sites are official pages for downloading official version of JDBC drivers.Oracle : s/jdbc/index-091264.htmlMysql : http://www.mysql.com/downloads/connector/j/A. Install the latest version of the Java SE SDK on your computer.B. Set up the classpath for a JDBC driver.The JDBC driver is not needed for compiling the java source but it is needed to execute theclass. There are so many ways to set up this classpath according to the OS, programmingtools and your preferences. This tutorial provides the case to use Eclipse.

If you use the eclipse, you can use following description. Eclipse main menu- Project - Properties - Java Build Path - Librarie Click Add External JARs - Select the JDBC driver. - Open Click Add External JARs - Select the JDBC driver. - Open

You can confirm the jar file is added then click OK.2. Establishing a ConnectionIn this step of the jdbc connection process, we load the driver class by calling Class.forName() withthe Driver class name as an argument. Once loaded, the Driver class creates an instance of itself.Example for loading JDBC driverString driverName "oracle.jdbc.driver.OracleDriver"; // for Oracle// String driverName “com.mysql.jdbc.Driver”; //for MySqltry {// Load the JDBC driverClass.forName(driverName);} catch (ClassNotFoundException e) {// Could not find the database driverSystem.out.println("ClassNotFoundException : " e.getMessage());}The JDBC DriverManager class defines objects which can connect Java applications to a JDBCdriver. DriverManager is considered the backbone of JDBC architecture. DriverManager classmanages the JDBC drivers that are installed on the system. Its getConnection() method is used toestablish a connection to a database. It uses a username, password, and a jdbc url to establish aconnection to the database and returns a connection object. A jdbc Connection represents asession/connection with a specific database. Within the context of a Connection, SQL, PL/SQLstatements are executed and results are returned. An application can have one or more connectionswith a single database, or it can have many connections with different databases.Example for JDBC connectionString serverName "linux.grace.umd.edu";String portNumber "1521";String sid "dbclass1";String url "jdbc:oracle:thin:@" serverName ":" portNumber ":" sid; // for Oracle//uri ”jdbc:mysql://server ip or address:port/database name”; //for Mysqltry {// Create a connection to the databaseconnection DriverManager.getConnection(url, username, password);catch (SQLException e) {// Could not connect to the databaseSystem.out.println(e.getMessage());}

Example for loading and connectionimport java.sql.Connection;import java.sql.DriverManager;import java.sql.SQLException;public class TestCon{Connection connection null;String driverName "oracle.jdbc.driver.OracleDriver"; // for Oracle// String driverName “com.mysql.jdbc.Driver”; //for MySqlString serverName "ginger.umd.edu"; // Use this server.String portNumber "1521";String sid "dbclass1";String url "jdbc:oracle:thin:@" serverName ":" portNumber ":" sid; // for Oracle//uri ”jdbc:mysql://server ip or address:port/database name”; //for MysqlString username "your user name"; // You should modify this.String password "your password"; // You should modify this.public TestCon() {}public boolean doConnection(){try {// Load the JDBC driverClass.forName(driverName);// Create a connection to the databaseconnection DriverManager.getConnection(url, username, password);} catch (ClassNotFoundException e) {// Could not find the database driverSystem.out.println("ClassNotFoundException : " e.getMessage());return false;} catch (SQLException e) {// Could not connect to the databaseSystem.out.println(e.getMessage());return false;}return true;}public static void main(String arg[]){TestCon con new TestCon();System.out.println("Connection : " con.doConnection());}}

If the output of the previous example is “Connection : true”, your environment setting and connectionis correct. If not, try to check the jdbc driver classpath, your username and your password3. Creating statements & executing queriesA Statement is an interface that represents a SQL statement. You execute Statement objects, and theygenerate ResultSet objects, which is a table of data representing a database result set. You needa Connection object to create a Statement object.There are three different kinds of statements. Statement: Used to implement simple SQL statements with no parameters.PreparedStatement: (Extends Statement.) Used for precompiling SQL statements that mightcontain input parameters. See Using Prepared Statements for more information.CallableStatement: (Extends PreparedStatement.) Used to execute stored procedures that maycontain both input and output parameters. See Stored Procedures for more information.Example for StatementStatement stmt null;try {stmt connection.createStatement();} catch (SQLException e ) {System.out.println(e.getMessage());}To execute a query, call an execute method from Statement such as the following: execute: Returns true if the first object that the query returns is a ResultSet object. Use thismethod if the query could return one or moreResultSet objects. Retrieve the ResultSet objectsreturned from the query by repeatedly calling Statement.getResutSet.executeQuery: Returns one ResultSet object.executeUpdate: Returns an integer representing the number of rows affected by the SQLstatement. Use this method if you are using INSERT,DELETE, or UPDATE SQL statements.Example for executeQueryString country ”D”;Statement stmt null;String query " SELECT * FROM CITY WHERE country '” country ”'”;try {stmt connection.createStatement();ResultSet rs stmt.executeQuery(query);while (rs.next()) {String name rs.getString(1); // or rs.getString("NAME");String coun rs.getString(2);String province rs.getString(3);int population rs.getInt(4);}stmt.close();} catch (SQLException e ) {

System.out.println(e.getMessage());}The re.next() return „true‟ until there is no more result.Example for executeQueryString population ”1705000”;String cityName ”Hamburg”;String province ”Hamburg”;Statement stmt null;try {stmt connection.createStatement();String sql "UPDATE CITY SET population '” population ”' WHERE NAME '” cityName ”' AND PROVINCE ‟” province ”‟";stmt.executeUpdate(sql);sstmt.close();} catch (SQLException e ) {System.out.println(e.getMessage());}Exmaple of simple JDBC programimport java.sql.Connection;import java.sql.DriverManager;import java.sql.ResultSet;import java.sql.SQLException;import java.sql.Statement;public class TestCon{Connection connection null;String driverName "oracle.jdbc.driver.OracleDriver"; // for Oracle// String driverName “com.mysql.jdbc.Driver”; //for MySqlString serverName "ginger.umd.edu";String portNumber "1521";String sid "dbclass1";String url "jdbc:oracle:thin:@" serverName ":" portNumber ":" sid; // forOracle//uri ”jdbc:mysql://server ip or address:port/database name”; //for MysqlString username "XXXXXXXX"; //your usernameString password "XXXXXXXX"; //your passwordpublic TestCon(){

}public boolean doConnection(){try {// Load the JDBC driverClass.forName(driverName);// Create a connection to the databaseconnection DriverManager.getConnection(url, username, password);} catch (ClassNotFoundException e) {// Could not find the database driverSystem.out.println("ClassNotFoundException : " e.getMessage());return false;} catch (SQLException e) {// Could not connect to the databaseSystem.out.println(e.getMessage());return false;}return true;}public void printCounryByCapital(String capital) throws SQLException{Statement stmt null;String query "SELECT * FROM COUNTRY WHERECAPITAL '" capital "'";stmt connection.createStatement();ResultSet rs stmt.executeQuery(query);while (rs.next()) {String name rs.getString(1); // or rs.getString("NAME");String code rs.getString(2);String cap rs.getString(3);String province rs.getString(4);int area rs.getInt(5);int population rs.getInt(6);System.out.println(" Name : " name);System.out.println(" Code : " code);System.out.println(" Capital : " cap);System.out.println(" Province : " province);System.out.println(" Area : " area);System.out.println(" Population : " population);}}public void printCityByCountry(String country) throws SQLException{Statement stmt null;String query " SELECT * FROM CITY WHERE country '" country "'";stmt connection.createStatement();ResultSet rs stmt.executeQuery(query);while (rs.next()) {String name rs.getString(1); // or rs.getString("NAME");String coun rs.getString(2);String province rs.getString(3);

int population rs.getInt(4);System.out.println(" Name : " name);System.out.println(" Country : " coun);System.out.println(" Province : " province);System.out.println(" Population : " population);}stmt.close();}public void updateCityPopulation(String cityName,String province,String population)throws SQLException{Statement stmt null;stmt connection.createStatement();String sql "UPDATE CITY SET population '" population "' WHERE NAME '" cityName "' ANDPROVINCE '" province "'";stmt.executeUpdate(sql);stmt.close();}public static void main(String arg[]){TestCon con new TestCon();System.out.println("Connection : " eption ex){System.out.println(ex.getMessage());}}}

Although JDBC was designed specifically to provide a Java interface to relational databases, you may find that you need to write Java code to access non-relational databases as well. JDBC Architecture Java application calls the JDBC library. JDBC loads a driver which talks to the database In general, to process any SQL statement with JDBC, you .

Related Documents:

Changes in This Release for Oracle Database JDBC Developer's Guide Changes in Oracle Database 12c Release 2 (12.2) xxx Part I Overview 1 Introducing JDBC 1.1 Overview of Oracle JDBC Drivers 1-1 1.2 Choosing the Appropriate Driver 1-3 1.3 Feature Differences Between JDBC OCI and Thin Drivers 1-4 1.4 Environments and Support 1-4 1.4.1 Supported JDK and JDBC Versions 1-5 1.4.2 JNI and Java .

The JDBC API provides a programming interface for data access of relational databases from the Java programming language. WebSphere Application Server V7 supports the following JDBC APIs: JDBC 4.0 (New in V7) JDBC 3.0 JDBC 2.1 and Optional Package API (2.0) In the following sec

Introduction to J2EE APIs (Servlet, JSP, EJB, JMS, JavaMail, JSF, JNDI) Introduction to Containers Tomcat as a Web Container Introduction of JDBC JDBC Architecture Data types in JDBC Processing Queries Database Exception Handling Discuss types of drivers JDBC Introduction and Need for JDBC

Bruksanvisning för bilstereo . Bruksanvisning for bilstereo . Instrukcja obsługi samochodowego odtwarzacza stereo . Operating Instructions for Car Stereo . 610-104 . SV . Bruksanvisning i original

JDBC / ODBC Driver The CDAP JDBC and ODBC drivers enable users to . (BI) applications with JDBC or ODBC support. The driver achieves this integration by translating Open Database Connectivity (JDBC/ODBC) calls from the application into SQL and passing the SQL queries to . Sensu, Cacti and Sp

JDBC on IBM i IBM offers three JDBC drivers for the access to IBM i: „IBM Toolbox for Java / JTOpen“, „IBM Native JDBC Driver“, „IBM JCC“ Third party distributors offer additional drivers, for example „HiT JDBC/400“ Toolbox and Native Driver are built and maintained by IBM Rochest

JDBC 2.0 - it provides JDBC API(JDBC 2.0 Core API and JDBC 2.0 Optional Package API). . The driver is a platform dependent because it uses ODBC which is depends on native libraries of . It's a 100% pure JAVA Driver so it's a platform independence. (2) No translation or middleware layers are used so consider as a faster than other .

Sharma, O.P. (1986). Text book of Algae- TATA McGraw-Hill New Delhi. Mycology 1. Alexopolous CJ and Mims CW (1979) Introductory Mycology. Wiley Eastern Ltd, New Delhi. 2. Bessey EA (1971) Morphology and Taxonomy of Fungi. Vikas Publishing House Pvt Ltd, New Delhi. 3. Bold H.C. & others (1980) – Morphology of Plants & Fungi – Harper & Row Public, New York. 4. Burnet JH (1971) Fundamentals .