`
iloveflower
  • 浏览: 79851 次
社区版块
存档分类
最新评论
  • iloveflower: 呵呵。好好学习。。。。。。。。。。。。
    java 读书
  • Eric.Yan: 看了一点,不过是电子版的……你这一说到提醒我了,还要继续学习哈 ...
    java 读书

JDBC basic

    博客分类:
  • JDBC
 
阅读更多
The JDBC ( Java Database Connectivity) API defines interfaces and classes for writing database applications in Java by making database connections. Using JDBC you can send SQL, PL/SQL statements to almost any relational database. JDBC is a Java API for executing SQL statements and supports basic SQL functionality. It provides RDBMS access by allowing you to embed SQL inside Java code. Because Java can run on a thin client, applets embedded in Web pages can contain downloadable 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 JDBC Program example.

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. We can change database engines without changing database code.

JDBC Basics – Java Database Connectivity Steps

Before you can create a java jdbc connection to the database, you must first import the
java.sql package.

import java.sql.*; The star ( * ) indicates that all of the classes in the package java.sql are to be imported.

1. Loading a database driver,

In this step of the jdbc connection process, we load the driver class by calling Class.forName() with the Driver class name as an argument. Once loaded, the Driver class creates an instance of itself. A client can connect to Database Server through JDBC Driver. Since most of the Database servers support ODBC driver therefore JDBC-ODBC Bridge driver is commonly used.
The return type of the Class.forName (String ClassName) method is “Class”. Class is a class in
java.lang package.



try {
Class.forName(”sun.jdbc.odbc.JdbcOdbcDriver”); //Or any other driver
}
catch(Exception x){
System.out.println( “Unable to load the driver class!” );
}

2. Creating a oracle jdbc Connection

The JDBC DriverManager class defines objects which can connect Java applications to a JDBC driver. DriverManager is considered the backbone of JDBC architecture. DriverManager class manages the JDBC drivers that are installed on the system. Its getConnection() method is used to establish a connection to a database. It uses a username, password, and a jdbc url to establish a connection to the database and returns a connection object. A jdbc Connection represents a session/connection with a specific database. Within the context of a Connection, SQL, PL/SQL statements are executed and results are returned. An application can have one or more connections with a single database, or it can have many connections with different databases. A Connection object provides metadata i.e. information about the database, tables, and fields. It also contains methods to deal with transactions.



JDBC URL Syntax::    jdbc: <subprotocol>: <subname>

JDBC URL Example:: jdbc: <subprotocol>: <subname>•Each driver has its own subprotocol
•Each subprotocol has its own syntax for the source. We’re using the jdbc odbc subprotocol, so the DriverManager knows to use the sun.jdbc.odbc.JdbcOdbcDriver.



try{
Connection dbConnection=DriverManager.getConnection(url,”loginName”,”Password”)
}
catch( SQLException x ){
System.out.println( “Couldn’t get connection!” );
}

3. Creating a jdbc Statement object,

Once a connection is obtained we can interact with the database. Connection interface defines methods for interacting with the database via the established connection. To execute SQL statements, you need to instantiate a Statement object from your connection object by using the createStatement() method.

Statement statement = dbConnection.createStatement();

A statement object is used to send and execute SQL statements to a database.

Three kinds of Statements

Statement: Execute simple sql queries without parameters.
Statement createStatement()
Creates an SQL Statement object.

Prepared Statement: Execute precompiled sql queries with or without parameters.
PreparedStatement prepareStatement(String sql)
returns a new PreparedStatement object. PreparedStatement objects are precompiled
SQL statements.

Callable Statement: Execute a call to a database stored procedure.
CallableStatement prepareCall(String sql)
returns a new CallableStatement object. CallableStatement objects are SQL stored procedure call statements.

4. Executing a SQL statement with the Statement object, and returning a jdbc resultSet.

Statement interface defines methods that are used to interact with database via the execution of SQL statements. The Statement class has three methods for executing statements:
executeQuery(), executeUpdate(), and execute(). For a SELECT statement, the method to use is executeQuery . For statements that create or modify tables, the method to use is executeUpdate. Note: Statements that create a table, alter a table, or drop a table are all examples of DDL
statements and are executed with the method executeUpdate. execute() executes an SQL
statement that is written as String object.

ResultSet provides access to a table of data generated by executing a Statement. The table rows are retrieved in sequence. A ResultSet maintains a cursor pointing to its current row of data. The next() method is used to successively step through the rows of the tabular results.

ResultSetMetaData Interface holds information on the types and properties of the columns in a ResultSet. It is constructed from the Connection object.

Test JDBC Driver Installation



import javax.swing.JOptionPane;

public class TestJDBCDriverInstallation_Oracle {

   public static void main(String[] args) {
  StringBuffer output  = new StringBuffer();
  output.append(”Testing oracle driver installation \n”);
  try {
  String className = “sun.jdbc.odbc.JdbcOdbcDriver”;
  Class driverObject = Class.forName(className);
  output.append(”Driver : “+driverObject+”\n”);
  output.append(”Driver Installation Successful”);
  JOptionPane.showMessageDialog(null, output);
    } catch (Exception e) {
    output  = new StringBuffer();
    output.append(”Driver Installation FAILED\n”);
    JOptionPane.showMessageDialog(null, output);
   System.out.println(”Failed: Driver Error: ” + e.getMessage());
  }
    }
}

Download JDBC Sample Code

Java JDBC Connection Example, JDBC Driver Example



import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;
import java.sql.SQLException;

public class JDBCDriverInformation {
static String userid=”scott”, password = “tiger”;
static String url = “jdbc:odbc:bob”; static Connection con = null;
public static void main(String[] args) throws Exception {
    Connection con = getOracleJDBCConnection();
    if(con!= null){
       System.out.println(”Got Connection.”);
       DatabaseMetaData meta = con.getMetaData();
       System.out.println(”Driver Name : “+meta.getDriverName());
       System.out.println(”Driver Version : “+meta.getDriverVersion());

    }else{
    System.out.println(”Could not Get Connection”);
    }
}

public static Connection getOracleJDBCConnection(){

try {
Class.forName(”sun.jdbc.odbc.JdbcOdbcDriver”); } catch(java.lang.ClassNotFoundException e) {
System.err.print(”ClassNotFoundException: “);
System.err.println(e.getMessage());
}

try {
   con = DriverManager.getConnection(url, userid, password);
} catch(SQLException ex) {
System.err.println(”SQLException: ” + ex.getMessage());
}

return con;
}

}

分享到:
评论

相关推荐

    JDBC.rar_ado ODBC jdbc_jdbc

    - ADO是Microsoft的数据库访问技术,主要用于.NET Framework和Visual Basic等环境。 - 由于本主题主要涉及JDBC,所以ADO在此仅作简要提及,它与JDBC在Java中的角色不同,但都用于数据库操作。 6. **JDBC连接步骤*...

    oracle-jdbc驱动14-10.2.0.2.0.zip

    Oracle JDBC驱动是Oracle数据库与Java应用程序之间通信的桥梁,它允许Java程序通过JDBC API连接并操作Oracle数据库。"oracle-jdbc驱动14-10.2.0.2.0.zip"是一个包含Oracle JDBC驱动特定版本(10.2.0.2.0)的压缩包...

    JDBC官方文档

    `connector-j-usagenotes-basic.html`可能包含关于事务管理的内容。JDBC支持自动提交和手动提交模式,可以使用Connection对象的setAutoCommit()和commit()方法控制事务。 ### 7. Spring框架中的JDBC配置 `connector...

    spring-data-jdbc-basic:Spring Data JDBC

    spring-data-jdbc-basic Spring Data JDBC基本介绍。 该项目尝试涵盖一对一和多对X关系。 该项目还包括使用DTO(Spring Data Core)进行投影的概念和客户行映射器(JDBC API)的概念

    JDBC数据库访问(七步).ppt

    * ODBC:Open DataBase Connectivity,是 Microsoft 公司开发的一套数据库系统应用程序的接口规范,即微软制定的一个 C 或 Basic 等语言与数据库的统一接口。 * JDBC:Java DataBase Connectivity,是 Sun 公司开发...

    instantclient-basic-windows.x64-12.2.0.1.0.zip oracle开源 轻量级数据库连接客户端

    通过以上描述,我们可以看出“instantclient-basic-windows.x64-12.2.0.1.0.zip”是一个全面的Oracle数据库连接解决方案,适合各种基于Windows的64位应用程序,特别是对于Java开发者来说,利用JDBC驱动可以轻松实现...

    JDBC Developers Guide Reference.rar

    additional basic features of Java and JDBC supported by the Oracle JDBC drivers. Chapter 4, "Overview of JDBC 2.0 Support" This chapter presents an overview of JDBC 2.0 features and describes the ...

    bootstrap+jdbc+struts2

    在名为“struts2_basic”的压缩包文件中,可能包含了一些基础的Struts2项目配置和示例代码,比如Struts2的配置文件(struts.xml),Action类的实现,以及相关的JSP页面。这些资源可以帮助初学者理解如何将Bootstrap、...

    oracle官方精简64位客户端-instantclient-basic-windows.x64-11.2.0.2.0

    Instant Client Package - Basic: All files required to run OCI, OCCI, and JDBC-OCI applications instantclient-basic-windows.x64-11.2.0.4.0.zip (54,956,947 bytes) Instant Client 程序包 — Basic(win64...

    在JDBC,hibernate中实现分页

    String sql = "SELECT COUNT(*) FROM basic WHERE deptid='" + data.getId() + "'"; try { Connection con = DriverManager.getConnection(a, b, c); Statement st = con.createStatement( ResultSet.TYPE_...

    Java Programming with Oracle JDBC

    This book covers a lot of material about Oracle's implementation of JDBC. It provides both the beginner and the advanced Oracle or Java user with all the information needed to be successful. ...

    instantclient-basic-nt-11.2.0.2.0

    这个特定版本"Instantclient-basic-nt-11.2.0.2.0"是适用于Windows NT(32位或64位)操作系统的,版本号11.2.0.2.0表明它是Oracle Database 11g Release 2的一个组件。 Oracle Instant Client主要包含以下组件和...

    instantclient-basic-nt-11.2.0.4.0.zip

    8. **ocijdbc11.dll**:Oracle JDBC驱动的组件,允许Java应用程序通过JDBC接口连接到Oracle数据库。 9. **genezi.exe**:这个工具用于生成特定平台和语言的本地化资源文件,帮助应用程序适应不同的语言环境。 10. ...

    instantclient-basic-windows.x64-11.2.0.4.0.zip

    instantclient-basic-windows.x64-11.2.0.4.0.zip,Oracle1164位官方客户端,可用于本地电脑未安装数据库的情况下,PLSQL连接Oracle数据库,注意,PLSQL也需要是64位版本的,客户端版本为11.2.0.4.0

    instant-client-basic-windows.x64-12.2.0.1.0.zip

    Basic Package - All files required to run OCI, OCCI, and JDBC-OCI applications Download instantclient-basic-windows.x64-12.2.0.1.0.zip (75,062,441 bytes) (cksum - 1462971172) The 12.2 Basic package ...

    oracle-instantclient11.2-jdbc-11.2.0.4.0-1.rar

    4. Basic Files:如ocijdbc11.jar,包含基础的Oracle数据库连接功能。 5. OCI(Oracle Call Interface):C语言编程接口,虽然主要面向C/C++开发者,但在某些情况下,Java应用也可能需要依赖它。 在Linux环境中,...

    instantclient-basiclite-windows.x64-12.2.0.1.0.zip

    2. **Basic Lite**: "Basic Lite"是Instant Client的一个特定版本,它包含了基本的数据库连接功能,适用于那些只需要基本数据库访问的场景,例如ODBC和JDBC连接。这个版本相比完整的Instant Client更小,但可能不...

    oracle-instantclient11.2-basic-11.2.0.4.0-1.x86_64.rpm

    oracle-instantclient11.2-basic-11.2.0.4.0-1.x86_64.rpm --基础包,为了运行OCI、OCCI、JDBC-OCI 这几个应用程序; oracle-instantclient11.2-sqlplus-11.2.0.4.0-1.x86_64.rpm --补充包/文件,是为了运行sql*plus...

    instantclient-basic-windows.x64-12.2.0.1.0。64位和32位的oracle instant client包

    - JDBC和JDBC Thin:Java数据库连接驱动,支持JDBC应用程序连接Oracle数据库。 - ODBC:开放数据库连接驱动,让Windows上的应用程序能通过ODBC API连接Oracle数据库。 2. **64位和32位的区别** - 64位版本的...

    instantclient-basic

    3. **ocijdbc12.jar**:Java Database Connectivity (JDBC) 驱动,供Java应用程序连接Oracle数据库使用。 4. **tnsnames.ora**:网络服务名配置文件,定义了数据库连接的逻辑名称及其对应的物理地址,方便用户通过...

Global site tag (gtag.js) - Google Analytics