database 1

在SQL SERVER2000中,打开查询分析器时,不要直接打开.sql文件,进行执行操作,比如说:

由于在查询分析器中,是执行脚本中的所有语句,所以当你在网页中将数据进行插入到数据库中的表中时如果直接打开表进行查询,那么,表中的数据将全部丢失。

所以需要在启动SQL SERVER时,文件----新建------然后看见下面的窗口,选择查询窗口

这时就在界面中创建了一个空白的窗口,用于查询,插入,修改等操作。







JDBC是一种执行SQL的Java API,并不是Java Database Connectivity的缩写。它为数据库开发人员提供了一系列标准的API函数,但其可以使用纯Java API来开发数据库应用程序。而且,JDBC在尽可能维持操作方便与简单的同时,还为研发人员提供了很大的弹性。

JDBC API为JAVA开发者提供了使用数据库的统一编程接口,它由一组JAVA类和接口组成。它使得开发人员可以使用纯JAVA的方式连接数据库并进行操作。

但是,在企业级环境中进行的数据库操作远远不只是连接数据库并执行语句,还需要考虑其他方面的要求,包括使用连接缓冲池优化资源的使用,实现分布式事务处理等。

两个常用的包:java.sql和javax.sql

前者中的类和借口主要针对基本的数据库编程服务,如生成连接,执行及准备语句和运行批处理查询等,同时也有一些高级的处理,比如,批处理更新,事务隔离和可滚动结果集等。

后者主要为数据库方面的高级操作提供类和接口。如为连接管理,分布式事务,原有的连接提供了更好的抽象,它引入了容器管理的连接池、分布式事务和行集等。在JDBC中可以让程序员建立SQL语句,切将它嵌入到JAVA API中,使得程序员在数据库与JAVA应用程序之间来去自如。

JDBC API分为两个不同的层次,应用层和驱动程序层。

应用层的API主要是数据库的应用程序开发者所使用的,如果只需要使用SQL语法来操作数据(新增,修改,删除或者查询等),那么该层就已经足够用了。

在使用JDBC应用层开发程序时,必须有开发商提供的JDBC驱动程序支持,这些JDBC驱动程序就是开发商利用驱动程序层的API撰写的。可以简单的认为,驱动程序层只有JDBC驱动程序开发商才会用得到。一般而言,厂商提供的JDBC驱动程序分为以下四大类:

JDBC-ODBC桥连接驱动程序(JDBC-ODBC bridge)

原生API驱动程序(Native-API Driver)

JDBC通过网络的纯JAVA驱动程序

原生协议以及纯JAVA驱动程序

类型一的驱动程序将JDBC数据转换成ODBC数据来源,然后利用ODBC与数据库连接。SUN在JDK中附有免费的JDBC-ODBC桥连接驱动程序(sun.jdbc.odbc.JdbcOdbcDriver)提供获取标准ODBC数据来源。不过,SUN强烈建议JDBC-ODBC桥连接器只是用来测试,不建议真正应用于WEB应用程序中,主要原因在于:性能差。



类型二是将JDBC指令转换成为DBMS所指定的原生码。也就是说,有一套不以JAVA撰写的函数库介于JAVA应用程序与数据库之间,这个函数库外层是JAVA程序,负责与JAVA应用程序沟通,而底层则是转换成为另一种语言,可能是C或者C++之类,负责与数据库沟通。使用这个驱动程序,可以让原生代码与数据库的沟通快过JAVA,不过一旦原生代码错误则可能危害到Server的安全。



类型三的驱动程序是一个3-Tier(层)的解决方案。这种驱动程序传送JDBC的指令到一个中介软件(Middleware),中介软件再将JDBC的要求传送到DBMS中,结果集合(ResultSet)也是通过中介软件传回到应用程序的。



类型四的驱动程序由纯JAVA编写,并且直接与数据库沟通,这种驱动程序不许要转换或者通过其他的中介软件就可以与数据库沟通,因此性能是最好的,也是比较安全的。

1.Driver接口。

每个数据库驱动程序都必须加载及注册JDBC驱动程序,对于JSP开发者而言,只需要使用Driver接口就可以了,在编程中要连接数据库,先装载特定厂商提供的的数据库驱动程序(Driver),在使用Class.forName()之前,应先使用import语句导入java.sql包,不同驱动程序的装载方法不同。

JDBC Driver

Class.forName("jdbc.driver_class_name");

JDBC-ODBC桥连接程序

Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

下面列出了数据库,驱动程序和URL(请将窗口最大化看下面的表格)

——————————————————————————————————————————----------------------------------------------------------

数据库名 驱动程序 URL

——————————————————————————————————————————----------------------------------------------------------

MSSQL com.microsoft.sqlserver.sqlServerDriver jdbc:Microsoft:sqlserver://[ip]:[port];user=[user];password=[password]

----------------------------------------------------------------------------------------------------------------------------------------------

JDBC-ODBC sun.jdbc.odbc.JdbcOdbcDriver jdbc:odbc:[odbcsource]

----------------------------------------------------------------------------------------------------------------------------------------------

Oracle oci8 oracle.jdbc.driver.OracleDriver jdbc:oracle:oci8@[sid]

----------------------------------------------------------------------------------------------------------------------------------------------

ORAthin Driver oracle.jdbc.driver.OracleDriver jdbc:oracle:thin:@[ip]:[port]:[sid]

----------------------------------------------------------------------------------------------------------------------------------------------

MySQL org.gjt.mm.mysql.Driver jdbc:mysql:/ip/database,user,password

----------------------------------------------------------------------------------------------------------------------------------------------



2.DriverManager

DriverManager(驱动程序管理器)类是JDBC(JAVA数据库连接)的管理层,作用于用户和驱动程序之间。DriverManager类跟踪可用的驱动程序,并在数据库和相应驱动程序之间建立连接。另外,DriverManager类也处理诸如驱动程序登陆时间限制及登陆和跟踪消息显示等事务。

当DriverManager激发getConnection()方法时,DriverManager首先从它已经加载的驱动程序池中找到一个可以接受该数据库URL的驱动程序,然后请求该驱动程序使用相关的数据库URL连接。这样getConnection方法就建立了与数据库的连接。

DriverManager类包含一系列的驱动程序类,这些驱动程序类已通过调用方法DriverManager.registerDriver对自己进行了注册。所有的驱动程序都必须包含一个静态部分,这个静态部分创建该类的实例,然后在加载该实例的DriverManager类时进行注册,这样,用户在正常情况下不会直接调用DriverManager.registerDriver方法,而是在加载驱动程序时由驱动程序自动调用。

可以通过两种方法来注册驱动程序:

一、调用发法Class.forName.此方法显示的加载驱动程序类。由于这种方法与外部设置无关,所以推荐使用这种方法加载驱动程序。

static Class<?> forName(String className)

Returns the Class object associated with the class or interface with the given string name.

二、将驱动程序添加到java.lang.System的属性jdbc.drivers中。

要隐式的添加一组驱动程序,只需要在jdbc.drivers系统属性中指定由冒号(:)分割的驱动程序类名即可。

初始化DriverManager类时,它搜索系统属性jdbc.drivers,如果用户已经输入了或多哥驱动程序,则DriverManager试图加载它们。

注意:所有驱动程序类的名称必须在用户的CLASSPATH中。

对DriverManager方法的第一次调用将自动加载这些驱动程序类。这里需要主义的是加载驱动程序的第二种方法需要持久的预设环境。如果这一点不能保证,调用方法Class.forName()显示的加载驱动程序就显得更加的安全,这也是引入特定驱动程序的方法,因为一旦DriverManager类被初始化,程序将不再检查jdbc.drivers属性列表。

在以上的两中情况中,新加载的驱动程序类都需要通过调用DriverManager.registerDriver类进行自我注册,加载类时将自动执行这一过程。在DriverManager中有这样一个非常重要的方法,就是getConnection(parameter...),在编程中通过这个方法获得一个连接。它有如下几种重载的方法:

static Connection getConnection(String url)

Attempts to establish a connection to the given database URL.

尝试建立一个给定的URL连接,调用此方法时,DriverManager将在已注册的驱动程序中选择恰当的驱动建立连接,URL的模式是dbc:subprotocol:subname

static Connection getConnection(String url, Properties info)

Attempts to establish a connection to the given database URL.

和上一个方法类似,不同的是需要提供一些属性,用于连接特定的数据库,至少包含user和password属性。

static Connection getConnection(String url, String user, String password)

Attempts to establish a connection to the given database URL.

连接URL指定的数据,用户名为user,密码为password

JDBC URL的标准语法如下:

<protocol>:<subprotocol>:<data source identifier>

主要通信协议,次通信协议,即驱动程序名称,数据来源。

eg. jdbc:odbc:mydb?user=user_name&password=user_password



3.Connection

Connection对象代表与数据库的连接,也就是连接已经加载的Driver和数据库,使用DriverManager的getConnection()方法可以建立Connection。在JDBC URL中定义数据库Connection的语法如下:

Connection conn=DriverManager.getConnection(url,login.password);

Connection接口是JSP数据库编程中使用最频繁的接口只一,读者一定要掌握它的使用,下面介绍其常用方法:

public interface Connection

A connection (session) with a specific database. SQL statements are executed and results are returned within the context of a connection.

A Connection object's database is able to provide information describing its tables, its supported SQL grammar, its stored procedures, the capabilities of this connection, and so on. This information is obtained with the getMetaData method.

Note: By default a Connection object is in auto-commit mode, which means that it automatically commits changes after executing each statement. If auto-commit mode has been disabled, the method commit must be called explicitly in order to commit changes; otherwise, database changes will not be saved.

A new Connection object created using the JDBC 2.1 core API has an initially empty type map associated with it. A user may enter a custom mapping for a UDT in this type map. When a UDT is retrieved from a data source with the method ResultSet.getObject, the getObject method will check the connection's type map to see if there is an entry for that UDT. If so, the getObject method will map the UDT to the class indicated. If there is no entry, the UDT will be mapped using the standard mapping.

A user may create a new type map, which is a java.util.Map object, make an entry in it, and pass it to the java.sql methods that can perform custom mapping. In this case, the method will use the given type map instead of the one associated with the connection.

For example, the following code fragment specifies that the SQL type ATHLETES will be mapped to the class Athletes in the Java programming language. The code fragment retrieves the type map for the Connection object con, inserts the entry into it, and then sets the type map with the new entry as the connection's type map.

java.util.Map map = con.getTypeMap();

map.put("mySchemaName.ATHLETES", Class.forName("Athletes"));

con.setTypeMap(map);

常用方法:

(1)close():关闭数据库的连接,在使用完连接后必须关闭,否则连接会持续保持,直到超时。

(2)commit():该方法用于提交对数据库的更改,使更改生效,需要注意的是,只有在将setAutoCommit()方法设置为false之后才有效,否则对数据库的更会自动提交到数据库。

(3)callableStratement prepareCall(String sql):创建一个用于执行存储过程的CallableStatment,SQL参数调用的存储过程,中间至少包含一个"?"占位符。

(4)getMetaData():该方法返回数据库元数据。

(5)isClosed():该方法判断数据库是否已经关闭。

(6)prepareStatement prepareStatment(String sql):该方法是使用指定的SQL语句创建一个预处理语句,SQL参数中往往包含一个或者多个"?"占位符。

(7)rollback():该方法用于回滚当前执行的操作,只有将setAutoCommit方法设置为false情况下才可以用。

(8)setAutoCommit(Boolean autoCommit):用于设置操作是否自动提交到数据库,默认情况下为true.

(9)Statement createStatement():生成一个执行SQL语句的Statement。

(10)Statement createStatement(int resultType,int resultSetConcurrency,int resultSetHoldability):创建一个Statement,并且产生指定类型的结果集(ResultSet).

(11)Statement createStatement(int resultType,int resultSetConcurrency):该方法用于创建一个Statement,并且产生指定类型的结果集,该方法包含两个参数

resultSetType:用来设定ResultSet对象中的光标是否能够上下自由移动,它的值只有三种:

static int TYPE_FORWARD_ONLY

The constant indicating the type for a ResultSet object whose cursor may move only forward.

static int TYPE_SCROLL_INSENSITIVE

The constant indicating the type for a ResultSet object that is scrollable but generally not sensitive to changes made by others.

static int TYPE_SCROLL_SENSITIVE

The constant indicating the type for a ResultSet object that is scrollable and generally sensitive to changes made by others.

当使用第一种时,表示ResultSet对象和JDBC1.0没有区别,只能使用next()方法,而后两者都可以让ResultSet对象中的光标能够随心所欲的上下移动,不过她们两者最大的区别在于:当ResultSet对象中的值有所改变时,TYPE_SCROLL_SENSITIVE能够取得改变后的值,而TYPE_SCROLL_INSENSITIVE却不能。

resultSetConcurrency:主要设定ResultSet对象是只读的(read-only)还是可以改变的(updatable),它的值有两种:

static int CONCUR_READ_ONLY

The constant indicating the concurrency mode for a ResultSet object that may NOT be updated.

static int CONCUR_UPDATABLE

The constant indicating the concurrency mode for a ResultSet object that may be updated.

第一种情况下,是只读的

第二种情况下的对象可以直接执行数据库的新增,修改和移除功能。



4.Statement

java.sql.Statement提供在基层连接上运行SQL语句的功能,并且访问结果。Connection接口提供了生成Statement的方法,一般情况下,通过connection.createStatement()方法就可以得到Statement的实例。

有三种Statement对象,它们都作为在给定连接上执行SQL语句的包容器:Statement,PrepareStatement(从Statement继承而来)和CallableStatement( 从PrepareStatement继承而来)。

Statement提供的方法很多,常用的如下:

void addBatch(String sql)

Adds the given SQL command to the current list of commmands for this Statement object.

增加批处理语句。

void cancel()

Cancels this Statement object if both the DBMS and driver support aborting an SQL statement.

void clearBatch()

Empties this Statement object's current list of SQL commands.

清除批处理语句。

void clearWarnings()

Clears all the warnings reported on this Statement object.

void close()

Releases this Statement object's database and JDBC resources immediately instead of waiting for this to happen when it is

automatically closed.

释放连接

boolean execute(String sql)

Executes the given SQL statement, which may return multiple results.

执行语句并返回是否有结果集。该方法主要用在如果你不知道正在执行的SQL是查询还是更新时,就可以利用这个方法,这通常会发生在应用程序执行动态建立SQL语句的场合,如果执行的是查询语句,则返回true,否则返回false.

boolean execute(String sql, int autoGeneratedKeys)

Executes the given SQL statement, which may return multiple results, and signals the driver that any auto-generated keys should be made available for retrieval.



boolean execute(String sql, int[] columnIndexes)

Executes the given SQL statement, which may return multiple results, and signals the driver that the auto-generated keys indicated in the given array should be made available for retrieval.



boolean execute(String sql, String[] columnNames)

Executes the given SQL statement, which may return multiple results, and signals the driver that the auto-generated keys indicated in the given array should be made available for retrieval.



int[] executeBatch()

Submits a batch of commands to the database for execution and if all commands execute successfully, returns an array of update counts.

提交一个命令批处理给数据库用来执行,如果所有命令都成功执行,返回一个更新数的数组。

ResultSet executeQuery(String sql)

Executes the given SQL statement, which returns a single ResultSet object.

执行查询数据库,以一个SQL语句做为自变量,返回一个ResultSet对象格式的查询结果。

int executeUpdate(String sql)

Executes the given SQL statement, which may be an INSERT, UPDATE, or DELETE statement or an SQL statement that returns nothing, such as an SQL DDL statement.

更新数据库,并返回更新的行数。它不但可以执行如:CREATE TABLE,DROP TABLE,ALTER TABLE等SQL DDL语句,还可以执行如INSERT,DELETE,UPDATE等SQL DML语句。返回值都为整数,其代表的意思是更新的数据笔数,但执行CREATE TABLE和DROP TABLE时,方法所传回的值都为0。

Connection getConnection()

Retrieves the Connection object that produced this Statement object.

返回生成Statement对象的连接对象

5.ResultSet

在Statment执行SQL语句时,有时会返回ResultSet结果集,该结果集往往包含的是查询的记录集。此结构抽象了运行SELECT语句的结果,提供了逐行访问记录的方法,通过它访问结果的不同字段。JDBC 2.1里增加了两种类型的ResultSet,允许向前和向后滚动。结果集一般是一个表,其中有查询返回的列的标题及相应的值。

通过ResultSet.next()方法把当前指针向下移动一位,最初它位于第一行之前,因此第一次调用next将把它的指针置于第一行,使它成为当前行,随着每次调用next导致指针向下移动,从上到下的顺序获取ResultSet行。

java.sql.ResultSet提供了检索不同类型字段的方法,如下所示:

getString():获取数据库中varchar,char等数据类型的对象。

getFloat():获取在数据库里是Float数据类型的对象。

getDouble():获取数据库里是Double Precision数据类型的对象。

getBoolean():该方法获取数据库中Boolean类型的对象。

getObject():该方法在SQL中无对应类型,可以得到序列化的对象。

getBlob():该方法用于获取数据库里的Blob(二进制大型对象)数据类型的对象。

getClob():该方法用于获取数据库里的Clob(字符串大型对象)数据类型的对象。



BOLB和CLOB

JDBC 2.0引入了两个最重要的数据类型,BLOB和CLOB,BLOB指的是二进制大型对象(Binary Large Object),CLOB指的是字符大型对象(Character Large Object)。他们都是用来处理大量数据的类型。分别代表大量的二进制数据和文字数据。它们使用串流来传送数据,可以直接抽取某些真正需要的数据,使得性能大大提升。JDBC 2.0支持两中与SQL中BLOB和CLOB对应的JAVA类型:java.sql.Blob和java.sql.Clob,如果从查询结果中取出数据,方式就像其他的数据类型一样,也就是getBlob()和getClob(),至于它们的存储方式,虽然JDBC2.0中没有提供用来构建BLOB和CLOB实体的借口,但是可以使用一下方式:

二进制数据:setBinaryStream()或setObject()

字符数据:setAsciiStream(),setUnicodeStream()或setObject()。



JNDI数据来源与连接池:

1.数据来源(Data Source):JSP提供DataSource的接口,用于在JSP程序代码之内减少一些数据库连接的写死问题。Connection的控管交给Container去控制,不用烦恼Connection管理上的问题。

2.连接池(Connection Pool):一般来说,如果每次JSP接受到请求时,就向数据库要求一个连接,当执行完就通知数据库断开连接,这样的方式会消耗大量的时间与资源。因为数据库每次建立Connection时,都要先将Connection加载内存,再来验证用户名和密码,等到一切通过之后,再与用户建立连接,断线后再重新来一次,如此冗长的程序,既耗时又没有效率,因此可以使用连接池来解决这个问题。

连接池的运作方式是一开始向数据库要求多个Connection存储在一个POOL(池)内,让需要的人从连接池内取得Connection,等到用完后再防会来,其实说穿了就是做了一个缓冲区,让JSP与数据库之间能够获得最大的执行效率。

上面1中提到的数据来源就负责提供连接池的功用,而读者开发人员需要做的就是从数据源中的连接池取得Connection,至于Connection的管理则交由数据来源处理,不过为了良好的习惯,还是将JSP不用的Connection对象还给数据来源。

3.JNDI(Java Naming and Directory Interface):JNDI主要提供应用程序所需资源上命名与目录的服务。

举个例子来说:如果有人实现将另一台机器上的磁盘驱动器连接到用户的机器上,即网络磁盘驱动器,用户在使用机器时分辨不出现在的磁盘驱动器是存在本地端还是另一台机器上,用户只是取得资源使用,不需要知道资源的位置在何处。

JNDI这个接口的底层基本上是LDAP,Lightweight Directory Access Protocol,轻量目录存取协议,Server将资源存放在类似LDAP上,当用户需要取用Server相关资源时,通过JNDI来取得资源即可。当需要取得DataSource对象时,就可以依靠JNDI完成。









首先,要有这个连接池的的驱动程序。(一般来说是.jar文件包)

其次,要把驱动程序放在正确的位置,比如C:/Tomcat 5.0/common/lib,这个目录里面放着很多的驱动程序。其实就是驱动程序类的打包文件。

每个数据库驱动程序都必须加载及注册JDBC驱动程序,对于JSP开发者而言,只需要使用Driver接口就可以了,在编程中要连接数据库,先装载特定厂商提供的的数据库驱动程序(Driver),在使用Class.forName()之前,应先使用import语句导入java.sql包,不同驱动程序的装载方法不同。

JDBC Driver

Class.forName("jdbc.driver_class_name");

JDBC-ODBC桥连接程序

Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

下面列出了数据库,驱动程序和URL(请将窗口最大化看下面的表格 宋体 5号字)

——————————————————————————————————————————----------------------------------------------------------

数据库名 驱动程序 URL

——————————————————————————————————————————----------------------------------------------------------

MSSQL com.microsoft.sqlserver.SQLServerDriver jdbc:Microsoft:sqlserver://[ip]:[port];user=[user];password=[password]

----------------------------------------------------------------------------------------------------------------------------------------------

JDBC-ODBC sun.jdbc.odbc.JdbcOdbcDriver jdbc:odbc:[odbcsource]

----------------------------------------------------------------------------------------------------------------------------------------------

Oracle oci8 oracle.jdbc.driver.OracleDriver jdbc:oracle:oci8@[sid]

----------------------------------------------------------------------------------------------------------------------------------------------

ORAthin Driver oracle.jdbc.driver.OracleDriver jdbc:oracle:thin:@[ip]:[port]:[sid]

----------------------------------------------------------------------------------------------------------------------------------------------

MySQL org.gjt.mm.mysql.Driver jdbc:mysql:/ip/database,user,password

----------------------------------------------------------------------------------------------------------------------------------------------



2.DriverManager

DriverManager(驱动程序管理器)类是JDBC(JAVA数据库连接)的管理层,作用于用户和驱动程序之间。DriverManager类跟踪可用的驱动程序,并在数据库和相应驱动程序之间建立连接。另外,DriverManager类也处理诸如驱动程序登陆时间限制及登陆和跟踪消息显示等事务。

当DriverManager激发getConnection()方法时,DriverManager首先从它已经加载的驱动程序池中找到一个可以接受该数据库URL的驱动程序,然后请求该驱动程序使用相关的数据库URL连接。这样getConnection方法就建立了与数据库的连接。

DriverManager类包含一系列的驱动程序类,这些驱动程序类已通过调用方法DriverManager.registerDriver对自己进行了注册。所有的驱动程序都必须包含一个静态部分,这个静态部分创建该类的实例,然后在加载该实例的DriverManager类时进行注册,这样,用户在正常情况下不会直接调用DriverManager.registerDriver方法,而是在加载驱动程序时由驱动程序自动调用。

可以通过两种方法来注册驱动程序:

一、调用发法Class.forName.此方法显示的加载驱动程序类。由于这种方法与外部设置无关,所以推荐使用这种方法加载驱动程序。

static Class<?> forName(String className)

Returns the Class object associated with the class or interface with the given string name.



二、将驱动程序添加到java.lang.System的属性jdbc.drivers中。

要隐式的添加一组驱动程序,只需要在jdbc.drivers系统属性中指定由冒号(:)分割的驱动程序类名即可。

初始化DriverManager类时,它搜索系统属性jdbc.drivers,如果用户已经输入了或多哥驱动程序,则DriverManager试图加载它们。

注意:所有驱动程序类的名称必须在用户的CLASSPATH中。

对DriverManager方法的第一次调用将自动加载这些驱动程序类。这里需要主义的是加载驱动程序的第二种方法需要持久的预设环境。如果这一点不能保证,调用方法Class.forName()显示的加载驱动程序就显得更加的安全,这也是引入特定驱动程序的方法,因为一旦DriverManager类被初始化,程序将不再检查jdbc.drivers属性列表。

在以上的两中情况中,新加载的驱动程序类都需要通过调用DriverManager.registerDriver类进行自我注册,加载类时将自动执行这一过程。在DriverManager中有这样一个非常重要的方法,就是getConnection(parameter...),在编程中通过这个方法获得一个连接。它有如下几种重载的方法:

static Connection getConnection(String url)

Attempts to establish a connection to the given database URL.

尝试建立一个给定的URL连接,调用此方法时,DriverManager将在已注册的驱动程序中选择恰当的驱动建立连接,URL的模式是dbc:subprotocol:subname

static Connection getConnection(String url, Properties info)

Attempts to establish a connection to the given database URL.

和上一个方法类似,不同的是需要提供一些属性,用于连接特定的数据库,至少包含user和password属性。

static Connection getConnection(String url, String user, String password)

Attempts to establish a connection to the given database URL.

连接URL指定的数据,用户名为user,密码为password

JDBC URL的标准语法如下:

<protocol>:<subprotocol>:<data source identifier>

主要通信协议,次通信协议,即驱动程序名称,数据来源。

eg. jdbc:odbc:mydb?user=user_name&password=user_password





实例讲解:使用连接池连接MS SQL SERVER 2000

连接MS SQL SERVER 2000时要把msbase.jar,mssqlserver.jar,msutil.jar三个文件复制到%Tomcat 5.0%/common/lib中,这是它的驱动程序,然后要设定Tomcat的server.xml,它位于%Tomcat 5.0%/conf/server.xml,需要建立一个站点,代码如下:添加到server.xml中的</host>前面。

<Context path="/Project" reloadable="true" docBase="Project">

<Resource name="jdbc/Project" auth="Container" type="javax.sql.DataSource"/>

<ResourceParams name="jdbc/Project">

<parameter>

<name>factory</name>

<value>org.apache.commons.dbcp.BasicDataSourceFactory</value>

</parameter>

<parameter>

<name>maxActive</name>

<value>100</value>

</parameter>

<parameter>

<name>maxIdle</name>

<value>30</value>

</parameter>

<parameter>

<name>maxWait</name>

<value>10000</value>

</parameter>

<parameter>

<name>username</name>

<value>sa</value>

</parameter>

<parameter>

<name>password</name>

<value>sunjavaduke</value>

</parameter>

<parameter>

<name>driverClassName</name>

<value>com.microsoft.jdbc.sqlserver.SQLServerDriver</value>

</parameter>

<parameter>

<name>url</name>

<value>jdbc:microsoft:sqlserver://127.0.0.1:1433;DatabaseName=Project;user=sa;password=sunjavaduke;</value>

</parameter>

</ResourceParams>

</Context>





server.xml配置完成之后,就可以对数据库进行操作了,具体代码如下:

<%@ page contentType="text/html;charset=gb2312" language="java" import="java.sql.*,javax.naming.*,javax.sql.*" errorPage="" %>

<html>

<head>

<meta http-equiv="Content-Type" content="text/html;charset=gb2312">

<title>连接池连接MS SQL SERVER 2000<title>

</head>

<body>

<%

out/print("使用连接池连接MS SQL SERVER 2000<br>");

out.println("<br>");

Context ctx=null;

DataSource ds=null;

Statment stmt=null;

ResultSet rs=null;

Connection con=null;

ResultSetMetaData md=null;

try{

ctx=new InitialContext();

ds=(DataSource)ctx.lookup("java:comp/env/jdbc/Project");

con=ds.getConnection();

stmt=con.createStatment();

rs=stmt.excuteQuery("select * from Test");

md=rs.getMetaData();

out.print(md.getColumnLabel(1)+" ");

out.print(md.getColumnLabel(2)+"<br>");

while(rs.next()){

out.print(rs.getInt(1)+" ");

out.print(rs.getString(2)+"<br>");

}

}catch(Exception e){

out.print(e);

}finally{

if(rs!=null) rs.close();

if(stmt!=null) stmt.close();

if(con!=null) con.close();

}

%>

</body>

</html>



需要注意的地方:

1.数据库驱动文件一定要放在指定的位置

2.<Context path="/Project" reloadable="true" docBase="Project">的用处在于建立一个虚拟路径,名字叫/Project,在manager/html中将会显示出来,docBase属性用于指出映射的路径,/Project名字可以随便起(比如改为DataBasePool),但是docBase一定要用准确的路径,相对路径或者绝对路径,最好用绝对路径,如

C:/Tomcat 5.0/webapps/Project

3. <parameter>

<name>username</name>

<value>sa</value>

</parameter>

<parameter>

<name>password</name>

<value>sunjavaduke</value>

</parameter>

<parameter>

<name>driverClassName</name>

<value>com.microsoft.jdbc.sqlserver.SQLServerDriver</value>

</parameter>

<parameter>

<name>url</name>

<value>jdbc:microsoft:sqlserver://127.0.0.1:1433;DatabaseName=Project;user=sa;password=sunjavaduke;</value>

</parameter>

4.<ResourceParams name="jdbc/Project">这是数据库源,必须要这样写。

<parameter>

<name>driverClassName</name>

<value>com.microsoft.jdbc.sqlserver.SQLServerDriver</value>

</parameter>

这里是微软的SQL SERVER 2000的驱动程序类名。

这里面设置了连接数据库的用户名和密码。这里SQL SERVER 2000的验证方式最好选用混合验证,也就是说要有sa这个用户。

5.一些类的介绍:

JNDI(Java Naming and Directory Interface):JNDI主要提供应用程序所需资源上命名与目录的服务。

举个例子来说:如果有人实现将另一台机器上的磁盘驱动器连接到用户的机器上,即网络磁盘驱动器,用户在使用机器时分辨不出现在的磁盘驱动器是存在本地端还是另一台机器上,用户只是取得资源使用,不需要知道资源的位置在何处。

JNDI这个接口的底层基本上是LDAP,Lightweight Directory Access Protocol,轻量目录存取协议,Server将资源存放在类似LDAP上,当用户需要取用Server相关资源时,通过JNDI来取得资源即可。当需要取得DataSource对象时,就可以依靠JNDI完成。

javax.sql.DataSource

public interface DataSource



A factory for connections to the physical data source that this DataSource object represents. An alternative to the DriverManager facility, a DataSource object is the preferred means of getting a connection. An object that implements the DataSource interface will typically be registered with a naming service based on the JavaTM Naming and Directory (JNDI) API.



The DataSource interface is implemented by a driver vendor. There are three types of implementations:



Basic implementation -- produces a standard Connection object

Connection pooling implementation -- produces a Connection object that will automatically participate in connection pooling. This implementation works with a middle-tier connection pooling manager.

Distributed transaction implementation -- produces a Connection object that may be used for distributed transactions and almost always participates in connection pooling. This implementation works with a middle-tier transaction manager and almost always with a connection pooling manager.

A DataSource object has properties that can be modified when necessary. For example, if the data source is moved to a different server, the property for the server can be changed. The benefit is that because the data source's properties can be changed, any code accessing that data source does not need to be changed.



A driver that is accessed via a DataSource object does not register itself with the DriverManager. Rather, a DataSource object is retrieved though a lookup operation and then used to create a Connection object. With a basic implementation, the connection obtained through a DataSource object is identical to a connection obtained through the DriverManager facility.



Method Summary

Connection getConnection()

Attempts to establish a connection with the data source that this DataSource object represents.

Connection getConnection(String username, String password)

Attempts to establish a connection with the data source that this DataSource object represents.



javax.naming.Context

public interface Context



This interface represents a naming context, which consists of a set of name-to-object bindings. It contains methods for examining and updating these bindings.



Object lookup(Name name)

Retrieves the named object.

Object lookup(String name)

Retrieves the named object.



public class InitialContext extends Object implements Context



This class is the starting context for performing naming operations.

All naming operations are relative to a context. The initial context implements the Context interface and provides the starting point for resolution of names.



When the initial context is constructed, its environment is initialized with properties defined in the environment parameter passed to the constructor, and in any application resource files. In addition, a small number of standard JNDI properties may be specified as system properties or as applet parameters (through the use of Context.APPLET). These special properties are listed in the field detail sections of the Context and LdapContext interface documentation.



JNDI determines each property's value by merging the values from the following two sources, in order:



The first occurrence of the property from the constructor's environment parameter and (for appropriate properties) the applet parameters and system properties.

The application resource files (jndi.properties).

For each property found in both of these two sources, or in more than one application resource file, the property's value is determined as follows. If the property is one of the standard JNDI properties that specify a list of JNDI factories (see Context), all of the values are concatenated into a single colon-separated list. For other properties, only the first value found is used.

The initial context implementation is determined at runtime. The default policy uses the environment property "java.naming.factory.initial", which contains the class name of the initial context factory. An exception to this policy is made when resolving URL strings, as described below.



When a URL string (a String of the form scheme_id:rest_of_name) is passed as a name parameter to any method, a URL context factory for handling that scheme is located and used to resolve the URL. If no such factory is found, the initial context specified by "java.naming.factory.initial" is used. Similarly, when a CompositeName object whose first component is a URL string is passed as a name parameter to any method, a URL context factory is located and used to resolve the first name component. See NamingManager.getURLContext() for a description of how URL context factories are located.



This default policy of locating the initial context and URL context factories may be overridden by calling NamingManager.setInitialContextFactoryBuilder().



NoInitialContextException is thrown when an initial context cannot be instantiated. This exception can be thrown during any interaction with the InitialContext, not only when the InitialContext is constructed. For example, the implementation of the initial context might lazily retrieve the context only when actual methods are invoked on it. The application should not have any dependency on when the existence of an initial context is determined.



When the environment property "java.naming.factory.initial" is non-null, the InitialContext constructor will attempt to create the initial context specified therein. At that time, the initial context factory involved might throw an exception if a problem is encountered. However, it is provider implementation-dependent when it verifies and indicates to the users of the initial context any environment property- or connection- related problems. It can do so lazily--delaying until an operation is performed on the context, or eagerly, at the time the context is constructed.



An InitialContext instance is not synchronized against concurrent access by multiple threads. Multiple threads each manipulating a different InitialContext instance need not synchronize. Threads that need to access a single InitialContext instance concurrently should synchronize amongst themselves and provide the necessary locking.



Constructor Summary

InitialContext()

Constructs an initial context.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值