DATABASE CONNECTIVITY IN JAVA JDBC Programming JDBC (Java Database Connectivity) is the specification of a Java API that allows Java programs to access DBMSs. The JDBC API consists of a set of interfaces and classes written in the Java programming language. Using these standard interfaces and classes, programmers can write applications that connect to databases, send queries written in structured query language (SQL), and process the results. JDBC Programming Steps 1)Create a connection to the database 1)Create a statement 2)Query the database 1)Close the result set 2)Close the statement 3)Close the connection Connect Query Process Results Close Register 1)Register the driver 1)Get a result set 2)Assign results to Java variables
DATABASE CONNECTIVITY IN JAVA A JDBC driver is needed to connect to a database. Registering a driver requires the class name of the driver. Example) JDBC-ODBC: sun.jdbc.odbc.JdbcOdbcDriver Oracle driver: oracle.jdbc.driver.OracleDriver MySQL: com.mysql.jdbc.Driver Loading the driver class Class.forName(String); Defined in java.lang.Class (no need to import) It is possible to load several drivers. The class DriverManager manages the loaded driver(s). STEP 1: Register
DATABASE CONNECTIVITY IN JAVA JDBC URL for a database Identifies the database to be connected Consists of three-parts: : : The DriverManager allows you to connect to a database using the specified JDBC driver, database location, database name, username and password. It returns a Connection object which can then be used to communicate with the database. java.sql.DriverManager Connection getConnection(String)//url Connection getConnection(String, String, String)//url, username, password STEP 2: Connect Protocol: JDBC is the only protocol in JDBC Subname: indicates the location and name of the database to be accessed. Syntax is driver specific Subname: indicates the location and name of the database to be accessed. Syntax is driver specific. DSN name should be used. Sub-protocol: identifies a database driver
DATABASE CONNECTIVITY IN JAVA DSN A Data Source Name (DSN) is the logical name that is used by Open Database Connectivity (ODBC) to refer to the driver and other information that is required to access data. Create a System DSN in Windows From Control Panel, open Administrative Tools, and then open Data Sources(ODBC). Click the System DSN tab, and then click Add. Click the database driver that corresponds with the database type to which you are connecting, and then click Finish. Type the data source name. Make sure that you choose a name that you can remember. You will need to use this name later. Click Select. Click the correct database, and then click OK. Click OK, and then click OK.