`
桔红糕
  • 浏览: 42522 次
  • 性别: Icon_minigender_2
  • 来自: 上海
社区版块
存档分类
最新评论

JDBC tutorial from SUN(3)

阅读更多
Lesson: JDBC Basics

    In this lesson you will learn the basics of the JDBC™ API.

        * We start by giving you set up instructions in Getting Started. This lesson sets up a basic development environment, including Java™ SE 6 and NetBeans™.

        * Setting Up a Database installs a testing database accessable through the NetBeans IDE, and installs its database driver.

        * Establishing a Connection connects you to your database.

        * Setting up Tables, Retrieving Values from Result Sets and Updating Tables all develop the process of configuring your database, sending queries and retrieving data from your database.
第一步:准备好运行环境。执行CRU等操作。熟悉statement, resultset等

    The next lesson discusses how to use joins, row sets, transactions and stored procedures.
第二步:joins?rowsets?事物和存储过程

    The final lesson describes how to create and run a complete JDBC application and provides some code examples for study.
第三步:完整的JDBC应用

Getting Started

    This lesson helps you to set up a JDBC™ development environment. This includes the following steps:

       1. Install the latest version of the Java™ platform on your machine. If you don't already have a database, it is recommended that you download the latest version of the NetBeans™ IDE and the Sun Application Server, which comes with Java DB.
不忘强烈推荐自家的NetBeans和 包含Java DB的Sun Application Server

                To install the Java platform, follow the instructions after downloading Java platform software and NetBeans. These downloads provide you with the JDBC package. JDBC includes the java.sql and javax.sql packages, which has the necessary interfaces and classes you'll need for developing JDBC applications.

                You can find the latest release at the following URL:

                    http://java.sun.com/products/JDK/CurrentRelease

       2. Install a driver on your machine.

                You also need to install a driver on your machine. If you installed NetBeans with the Sun Application Server, then you have the driver that you need.

                Note: A JDBC driver can come from many sources: database software, such as Java DB, a JDBC driver vendor such as DataDirect, Oracle, MySQL, or an ISV/OEM such as Sun. Your driver should include instructions for installing it. For a JDBC driver written for specific Database Management Systems (DBMS), installation consists of copying the driver onto your machine. No special configuration is needed.

       3. Install your Database Management System (DBMS) if needed.

                If you do not already have a Database Management System (DBMS) installed, follow the vendor's instructions for installation. You can download the Java DB database, which comes bundled with the Sun Application Server:
                Free Trial Download, and the NetBeans IDE. as well.

                Types of Drivers

四种驱动程序——每个介绍jdbc的文章都要说到这个话题。但似乎没有什么真正的应用意义。
                There are many possible implementations of JDBC drivers. These implementations are categorized as follows:
                    o Type 1 - drivers that implement the JDBC API as a mapping to another data access API, such as ODBC. Drivers of this type are generally dependent on a native library, which limits their portability. The JDBC-ODBC Bridge driver is an example of a Type 1 driver.

                    o Type 2 - drivers that are written partly in the Java programming language and partly in native code. These drivers use a native client library specific to the data source to which they connect. Again, because of the native code, their portability is limited.

                    o Type 3 - drivers that use a pure Java client and communicate with a middleware server using a database-independent protocol. The middleware server then communicates the client?s requests to the data source.

                    o Type 4 - drivers that are pure Java and implement the network protocol for a specific data source. The client connects directly to the data source.

                Check which driver type comes with your DBMS on the JDBC Data Access API Drivers page. Java DB ships with two Type 4 drivers, an Embedded driver and a Network Client Driver.

jdbc目前的driverlist 以及driver所支持的jdbc类型。
http://developers.sun.com/product/jdbc/drivers


Setting Up a Database

    Before you write a JDBC™ application, you need to set up a database called COFFEEBREAK. You learn how to create a database through your vendor documentation. Once you have set up the COFFEEBREAK database, continue with this lesson.

    We strongly suggest that you use the Java DB database bundled with Netbeans, to work through this tutorial. Directions for setting up and connecting to the Java DB™ and using the NetBeans™ IDE can be found here.
    Overview
    Assume that our sample database is being used by the proprietor of a small coffee house called The Coffee Break, where coffee beans are sold by the pound and brewed coffee is sold by the cup. To keep things simple, also suppose that the proprietor needs only two tables, one for types of coffee and one for coffee suppliers.

    To store data in the database, you create tables. Later, when you learn about creating the tables used as examples in this tutorial, the tables will be in the default database. We purposely kept the size and number of tables small to keep things manageable.

    Once you have created the database and tables to store the data, you'll a open a connection with your DBMS. You also need to know some SQL code. After that, you'll discover how easy it is to use JDBC to pass SQL statements to your DBMS and then process the results that are returned.

Establishing a Connection

    First, you need to establish a connection with the DBMS you want to use. Typically, a JDBC™ application connects to a target data source using one of two mechanisms:

通过两种方式连接数据库:DriverManager和DataSource。

        * DriverManager:   This fully implemented class requires an application to load a specific driver, using a hardcoded URL. As part of its initialization, the DriverManager class attempts to load the driver classes referenced in the jdbc.drivers system property. This allows you to customize the JDBC Drivers used by your applications.
更推荐DataSource方式,它使底层数据源更透明
        * DataSource:   This interface is preferred over DriverManager because it allows details about the underlying data source to be transparent to your application. A DataSource object's properties are set so that it represents a particular data source.

    Establishing a connection involves two steps: Loading the driver, and making the connection.
    Loading the Driver

    Loading the driver you want to use is very simple. It involves just one line of code in your program. To use the Java DB driver, add the following line of code:

       Class.forName("org.apache.derby.jdbc.EmbeddedDriver");


    Your driver documentation provides the class name to use. In the example above, EmbeddedDriver is one of the drivers for Java DB.

    Calling the Class.forName automatically creates an instance of a driver and registers it with the DriverManager, so you don't need to create an instance of the class. If you were to create your own instance, you would be creating an unnecessary duplicate, but it would do no harm.

    After you have loaded a driver, it can make a connection with a DBMS.
    Making the Connection

    The second step in establishing a connection is to have the appropriate driver connect to the DBMS.
    Using the DriverManager Class

    The DriverManager class works with the Driver interface to manage the set of drivers available to a JDBC client. When the client requests a connection and provides a URL, the DriverManager is responsible for finding a driver that recognizes the URL and for using it to connect to the corresponding data source. Connection URLs have the following form:
    jdbc:derby:<dbName>[propertyList]

一个数据库可以在以下这些位置————very 奇怪
    The dbName portion of the URL identifies a specific database. A database can be in one of many locations: in the current working directory, on the classpath, in a JAR file, in a specific Java DB database home directory, or in an absolute location on your file system.

    If you are using a vendor-specific driver, such as Oracle, the documentation will tell you what subprotocol to use, that is, what to put after jdbc: in the JDBC URL. For example, if the driver developer has registered the name OracleDriver as the subprotocol, the first and second parts of the JDBC URL will be jdbc.driver.OracleDriver . The driver documentation will also give you guidelines for the rest of the JDBC URL. This last part of the JDBC URL supplies information for identifying the data source.

    The getConnection method establishes a connection:
        Connection conn = DriverManager.getConnection("jdbc:derby:COFFEES");


    In place of " myLogin " you insert the name you use to log in to the DBMS; in place of " myPassword " you insert your password for the DBMS. So, if you log in to your DBMS with a login name of " Fernanda " and a password of " J8, " just these two lines of code will establish a connection:
        String url = "jdbc:derby:Fred";
        Connection con = DriverManager.getConnection(url, "Fernanda", "J8");


    If one of the drivers you loaded recognizes the JDBC URL supplied to the method DriverManager.getConnection, that driver establishes a connection to the DBMS specified in the JDBC URL. The DriverManager class, true to its name, manages all of the details of establishing the connection for you behind the scenes. Unless you are writing a driver, you probably won't use any of the methods in the interface Driver, and the only DriverManager method you really need to know is DriverManager.getConnection
除非你要写个Driver,否则你只要知道DriverManager.getConnection这一个方法就可以了
    The connection returned by the method DriverManager.getConnection is an open connection you can use to create JDBC statements that pass your SQL statements to the DBMS. In the previous example, con is an open connection, and you use it in the examples that follow.
    Using a DataSource Object for a connection
    Using a DataSource object increases application portability by making it possible for an application to use a logical name for a data source instead of having to supply information specific to a particular driver. The following example shows how to use a DataSource to establish a connection:

    You can configure a DataSource using a tool or manually. For example, Here is an example of a DataSource lookup:
为什么ds还要强转?
         InitialContext ic = new InitialContext()
         
         DataSource ds = ic.lookup("java:comp/env/jdbc/myDB");
         Connection con = ds.getConnection();
         DataSource ds = (DataSource) org.apache.derby.jdbc.ClientDataSource()
         ds.setPort(1527);
         ds.setHost("localhost");
         ds.setUser("APP")
         ds.setPassword("APP");
         
        Connection con = ds.getConnection(); 


    DataSource implementations must provide getter and setter methods for each property they support. These properties typically are initialized when the DataSource object is deployed.

        VendorDataSource vds = new VendorDataSource();
        vds.setServerName("my_database_server");
        String name = vds.getServerName();


    JDBC-ODBC Bridge Driver

    For normal use, you should obtain a commercial JDBC driver from a vendor such as your database vendor or your database middleware vendor. The JDBC-ODBC Bridge driver provided with JDBC is recommended only for development and testing, or when no other alternative is available.

分享到:
评论
2 楼 shenyu 2008-05-13  
想起了分段事务的代码,不知道这样写可以不?

//申请资源,如数据库连接

try {
//第一部分操作
String saveName = "a";
con.setSavepoint(saveName);
try{
//开始数据库操作
//CRUD
//第一步分的操作结束

saveName = "b";
con.setSavepoint(saveName);
} catch (SQLException e) {
con.rollback(saveName);//回滚致最后一次SavePoint
//log操作
}

//第二部分操作
try{
//开始数据库操作
//CRUD
//第二步分的操作结束

saveName = "c";
con.setSavepoint(saveName);
} catch (SQLException e) {
con.rollback(saveName); //回滚致最后一次SavePoint
//log操作
}

//第三部分操作
try{
//开始数据库操作
//CRUD
//第三步分的操作结束

saveName = "d";
con.setSavepoint("a");
} catch (SQLException e) {
con.rollback(saveName); //回滚致最后一次SavePoint
//log操作
}
} finally {
con.commit();
}

//释放资源,如数据库连接
1 楼 shenyu 2008-05-13  
从橘子老师这里真是学到了不少东西。不过有些E文看不明白,还是要好好请教。

相关推荐

    jdbc api tutorial and reference

    JDBC(Java Database Connectivity)是Java平台上的一个标准接口,由Sun Microsystems开发并纳入Java Development Kit (JDK) 中,它为Java程序员提供了一种统一的方法来访问各种数据库。《JDBC API教程与参考》是由...

    JDBC API Tutorial and Reference 3rd Edition

    《JDBC API Tutorial and Reference 3rd Edition》是数据库编程领域一本重要的参考资料,它深入浅出地介绍了Java数据库连接(JDBC)API的使用方法。这本书由Addison Wesley出版,旨在帮助开发者理解和掌握如何在Java...

    JDBC API Tutorial and Reference 3rd Edition (2003).chm

    JDBC™ API Tutorial and Reference, Third Edition By Maydene Fisher, Jon Ellis, Jonathan Bruce Publisher : Addison Wesley Pub Date : June 13, 2003 ISBN : 0-321-17384-8

    Sun Java Tutorial(错误/参见另一个文件)

    实在对不起大家,之前传的这个有问题。是我的疏忽,不是我有意骗大家分。我重新上传了。这个就不要再下了。 #非常棒的一本入门教程,配合java api doc 中文看,黄金搭档。

    JDBC API教程与参考手册(第三版)前言+目录+第一,二章

    ResultSet rs = stmt.executeQuery("SELECT * FROM users"); // 处理结果集 while (rs.next()) { System.out.println(rs.getString("name") + ", " + rs.getString("email")); } // 关闭资源 rs.close(); ...

    SUN Java certificate tutorial.rar

    在这个"SUN Java certificate tutorial.rar"压缩包中,很显然包含了一个关于如何理解和使用Java证书的教学资源。 首先,Java证书是公钥基础设施(PKI)的一部分,它由可信的证书颁发机构(CA)签署,以确认一个实体...

    j3d_tutorial\ j3d教程sun官方版

    "j3d_tutorial\ j3d教程sun官方版" 提供的是Sun官方的Java 3D教程,这是一份非常宝贵的资源,对于学习和理解Java 3D编程至关重要。 Java 3D API允许开发者通过对象模型来构建3D世界,这些对象包括几何形状、变换、...

    A Complete Tutorial on Tree Based Modeling from Scratch (in R——& Python)

    通过一个实例代码完全描述了决策树的构造过程。具有很好的学习和借鉴意义。(PDF文档)

    FMC-IMAGEON - Building a Video Design from Scratch Tutorial

    在这个"FMC-IMAGEON - Building a Video Design from Scratch Tutorial"中,我们将会深入探讨如何从零开始构建一个视频设计项目。教程的标题暗示了这是一次全面的学习过程,旨在帮助用户掌握视频设计的基础知识和...

    JDBC.pdf

    - JDBC教程:[http://java.sun.com/docs/books/tutorial/jdbc/](http://java.sun.com/docs/books/tutorial/jdbc/) - 可用JDBC驱动列表:[http://industry.java.sun.com/products/jdbc/drivers/]...

    J2EE Tutorial中文版

    Sun权威教程--《J2EE Tutorial中文版》 作者:Stephanie Bodoff,Dale Green,Kim Haase,Eric Jendrock,Monica Pawlan,Beth Stearns 翻译参与人员:sharetop,worldheart,zhaoy,bruce等 出版商:铁道出版社...

    .-.jdbc.api.tutorial.and.reference

    JDBC API知道和开发引用

    JDBC API教程与参考手册(第三版)其余部分 PART 3

    JDBC API教程与参考手册(第三版)其余部分 PART 3

    ns3-tutorial

    ns-3 Tutorial ns-3 是一个开源的网络仿真器,旨在提供一个灵活、灵活和可扩展的网络仿真环境。ns-3 项目的主要目标是提供一个功能强大、灵活和可扩展的网络仿真环境,帮助研究人员和开发人员设计、develop和测试...

    Java 3D Tutorial v1.6.2 (Java 3D API v1.2)

    目前为止能找到的最新版本。资料很难得。 Java 3D Tutorial v1.6.2 (Java 3D API v1.2) Getting Started with the Java 3D API A Tutorial for Beginners

    The J2EE Tutorial-中文版.pdf

    - JDBC教程:[http://java.sun.com/docs/books/tutorial/jdbc](http://java.sun.com/docs/books/tutorial/jdbc) - 多线程教程:[http://java.sun.com/docs/books/tutorial/essential/threads]...

    java 3d tutorial 指南 入门实例

    由于Sun公司经常发布新版本,建议直接访问其网站查找最新资料。在撰写本文时,最新的Java版本是6.3,可在http://java.sun.com/javase/downloads/index.jsp找到。而Java 3D的当前扩展版本为1.5.1,可访问...

Global site tag (gtag.js) - Google Analytics