JDBC连接常用数据库

1、Oracle8/8i/9i数据库(thin模式)

    Class.forName(“oracle.jdbc.driver.OracleDriver”).newInstance();

    String url=”jdbc:oracle:thin:@localhost:1521:orcl”;

    //orcl为数据库的SID

    String user=”test”;

    String password=”test”;

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

    2、DB2数据库

    Class.forName(“com.ibm.db2.jdbc.app.DB2Driver “).newInstance();

    String url=”jdbc:db2://localhost:5000/sample”;

    //sample为你的数据库名

    String user=”admin”;

    String password=””;

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

    3、Sql Server7.0/2000数据库

    Class.forName(“com.microsoft.jdbc.sqlserver.SQLServerDriver”).newInstance();

    String url=”jdbc:microsoft:sqlserver://localhost:1433;DatabaseName=mydb”;

    //mydb为数据库

    String user=”sa”;

    String password=””;

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

    4、Sybase数据库

    Class.forName(“com.sybase.jdbc.SybDriver”).newInstance();

    String url =” jdbc:sybase:Tds:localhost:5007/myDB”;

    //myDB为你的数据库名

    Properties sysProps = System.getProperties();

    SysProps.put(“user”,”userid”);

    SysProps.put(“password”,”user_password”);

    Connection conn= DriverManager.getConnection(url, SysProps);

    5、Informix数据库

    Class.forName(“com.informix.jdbc.IfxDriver”).newInstance();

    String url =

    “jdbc:informix-sqli://123.45.67.89:1533/myDB:INFORMIXSERVER=myserver;

    user=testuser;password=testpassword”;

    //myDB为数据库名

    Connection conn= DriverManager.getConnection(url);

    6、MySQL数据库

    Class.forName(“org.gjt.mm.mysql.Driver”).newInstance();

    String url =”jdbc:mysql://localhost/myDB user=soft&password=soft1234&useUnicod

    e=true&characterEncoding=8859_1″

    //myDB为数据库名

    Connection conn= DriverManager.getConnection(url);

    7、PostgreSQL数据库

    Class.forName(“org.postgresql.Driver”).newInstance();

    String url =”jdbc:postgresql://localhost/myDB”

    //myDB为数据库名

    String user=”myuser”;

    String password=”mypassword”;

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

连接池基础与dbcp连接池的使用

1.JDBC数据库连接池的必要性

在使用开发基于数据库的web程序时,传统的模式基本是按以下步骤:  

在主程序(如servletbeans)中建立数据库连接。

进行sql操作

断开数据库连接。

这种模式开发,存在的问题:

普通的JDBC数据库连接使用 DriverManager 来获取,每次向数据库建立连接的时候都要将 Connection 加载到内存中,再验证用户名和密码(得花费0.05s1s的时间)。需要数据库连接的时候,就向数据库要求一个,执行完成后再断开连接。这样的方式将会消耗大量的资源和时间。数据库的连接资源并没有得到很好的重复利用.若同时有几百人甚至几千人在线,频繁的进行数据库连接操作将占用很多的系统资源,严重的甚至会造成服务器的崩溃。

对于每一次数据库连接,使用完后都得断开。否则,如果程序出现异常而未能关闭,将会导致数据库系统中的内存泄漏,最终将导致重启数据库。

这种开发不能控制被创建的连接对象数,系统资源会被毫无顾及的分配出去,如连接过多,也可能导致内存泄漏,服务器崩溃.

2.数据库连接池(connection pool

为解决传统开发中的数据库连接问题,可以采用数据库连接池技术。

数据库连接池的基本思想就是为数据库连接建立一个“缓冲池”。预先在缓冲池中放入一定数量的连接,当需要建立数据库连接时,只需从“缓冲池”中取出一个,使用完毕之后再放回去。

数据库连接池负责分配、管理和释放数据库连接,它允许应用程序重复使用一个现有的数据库连接,而不是重新建立一个

数据库连接池在初始化时将创建一定数量的数据库连接放到连接池中,这些数据库连接的数量是由最小数据库连接数来设定的。无论这些数据库连接是否被使用,连接池都将一直保证至少拥有这么多的连接数量。连接池的最大数据库连接数量限定了这个连接池能占有的最大连接数,当应用程序向连接池请求的连接数超过最大连接数量时,这些请求将被加入到等待队列中。

3.数据库连接池技术的优点

(1)资源重用:由于数据库连接得以重用,避免了频繁创建,释放连接引起的大量性能开销。在减少系统消耗的基础上,另一方面也增加了系统运行环境的平稳性。

(2)更快的系统反应速度:数据库连接池在初始化过程中,往往已经创建了若干数据库连接置于连接池中备用。此时连接的初始化工作均已完成。对于业务请求处理而言,直接利用现有可用连接避免了数据库连接初始化和释放过程的时间开销,从而减少了系统的响应时间

(3)新的资源分配手段对于多应用共享同一数据库的系统而言,可在应用层通过数据库连接池的配置实现某一应用最大可用数据库连接数的限制避免某一应用独占所有的数据库资源.

(4)统一的连接管理,避免数据库连接泄露在较为完善的数据库连接池实现中,可根据预先的占用超时设定,强制回收被占用连接,从而避免了常规数据库连接操作中可能出现的资源泄露

4.两种开源的数据库连接池:

   (1)JDBC 的数据库连接池使用 javax.sql.DataSource 来表示,DataSource 只是一个接口,该接口通常由服务器(Weblogic, WebSphere, Tomcat)提供实现。

(2)DBCP 数据库连接池是 Apache 软件基金组织下的开源连接池实现, 该连接池依赖该组织下的另一个开源系统:Common-pool. 如需使用该连接池实现,应在系统中增加如下两个 jar 文件:Commons-dbcp.jar:连接池的实现 Commons-pool.jar:连接池依赖库

(5)DBCP连接池使用的两种形式

   (1):直接设置参数的形式:

//创建数据源对象

BasicDataSource bds = new BasicDataSource();

//设置连接数据库的驱动

bds.setDriverClassName(“com.mysql.jdbc.Driver”);

//设置连接数据库的url

bds.setUrl(“jdbc:mysql://localhost:3306/test”);

//设置连接数据库的用户名

bds.setUsername(“root”);

//设置连接数据库的密码

bds.setPassword(“root”);

//设置连接池启动时的初始值

bds.setInitialSize(5);

//设置连接池的最大值

bds.setMaxActive(50);

//最大空闲值.当经过一个高峰时间后,连接池可以慢慢将已经

//用不到的连接慢慢释放一部分,一直减少到maxIdle为止

bds.setMaxIdle(20);

//最小空闲值.当空闲的连接数少于该值时,连接池就会预申请一些连接,

//以避免洪峰来时再申请而造成的性能开销

bds.setMinIdle(5);

得到连接:Connection conn = dbs.getConnection();

……..

    (2):读取配置文件(properties)的方式。

                   //构建properties对象

                   Properties properties = new Properties();

                   //加载配置文件

        properties.load(inputSream);

                   //BasicDataSourceFactory利用属性文件的信息创建BasicDataSource数据源

dataSource=BasicDataSourceFactory.createDataSource(properties);

//获取连接

Connection conn = dataSource.getConnection();

 

配置文件内容形式如下(注意key严格遵循大小写)

#连接字符串

url=jdbc:mysql://localhost:3306/test

#用户名

username=root

#密码

password=root

#驱动的类路径

driverClassName=com.mysql.jdbc.Driver

#连接池启动时的初始值

initialSize=1

#连接池的最大值

maxActive=50

#最大空闲数

maxIdle=20

#最小空闲数

                   minIdle=5        

ibatis新手上路

概念:

iBATIS , 又是一个O/R Mapping的解决方案(例如 hibernate的ORM 也是解决方案之一.)

网上很多人便将其称为ORM , 但是用过的人, 应该都会觉得并不恰当.

与其称之为一个OR Mapping , 倒不如叫它SQL Mapping…

iBATIS 的特点是小巧, 简单. 但是要求需要熟悉SQL , 不像hibernate那样, 可以让你一句sql 都不用写

同时, 我觉得要写挺多的配置文件的. 可能会比较繁琐.

sample

还是拿最简单的 User 类来测试. User.java  

public class User {  

 

    private int id;  

    private String username;  

    private String userpwd;  

    private String userdesc;  

 

        //Sets and Gets…  



public class User {

private int id;

private String username;

private String userpwd;

private String userdesc;

        //Sets and Gets…

接下来… 马上看看… dao里面的一个方法有多简单~~ UserDao.java

 

Java代码 

public static List getAllUsers() throws SQLException {  

                  

               SqlMapClient sqlMap = Utils.getSqlmap();  

       try {  

            List li = sqlMap.queryForList(“getAllUsers”);  

              

       } catch (SQLException e) {  

               e.printStackTrace();  

        }  

        return li;  



public static List getAllUsers() throws SQLException {

               

               SqlMapClient sqlMap = Utils.getSqlmap();

try {

List li = sqlMap.queryForList(“getAllUsers”);

} catch (SQLException e) {

e.printStackTrace();

}

return li;

是的, dao里面的一个方法只需要这么几句话.

看看怎么实现的吧…

首先, 我们需要一个跟 User 类对应的 配置文件 User.xml(名字相同并不是硬性规定, 只是方便管理)

Xml代码 

< xml version=”1.0″ encoding=”UTF-8″  > 

<!DOCTYPE sqlMap PUBLIC “-//ibatis.apache.org//DTD SQL Map 2.0//EN”  

   “http://ibatis.apache.org/dtd/sql-map-2.dtd”> 

 

<sqlMap namespace=”User”> 

 

        <typeAlias alias=”user” type=”pojo.User”/> 

 

   <select id=”getAllUsers” resultClass=”user”> 

       select * from user order by id;   

    </select> 

</sqlMap> 

< xml version=”1.0″ encoding=”UTF-8″  >

<!DOCTYPE sqlMap PUBLIC “-//ibatis.apache.org//DTD SQL Map 2.0//EN”

   “http://ibatis.apache.org/dtd/sql-map-2.dtd”>

<sqlMap namespace=”User”>

        <typeAlias alias=”user” type=”pojo.User”/>

<select id=”getAllUsers” resultClass=”user”>

select * from user order by id;

</select>

</sqlMap>

接下来, 需要一个另一个配置文件, 将User.xml 加入 其中, 同时还要在里面配置数据源—- 即数据库的连接等等…   SqlMapConfig.xml

Xml代码 

< xml version=”1.0″ encoding=”UTF-8″ > 

 

<!DOCTYPE sqlMapConfig PUBLIC “-//ibatis.apache.org//DTD SQL Map Config 2.0//EN”  

    “http://ibatis.apache.org/dtd/sql-map-config-2.dtd”> 

<sqlMapConfig> 

      

   <properties resource=”sqlmap.properties”/> 

         

    <transactionManager type=”JDBC”> 

        <dataSource type=”SIMPLE”>      

           <property name=”JDBC.Driver” value=”${jdbc.driverClassName}” /> 

            <property name=”JDBC.ConnectionURL” value=”${jdbc.url}” /> 

           <property name=”JDBC.Username” value=”${jdbc.username}” /> 

            <property name=”JDBC.Password” value=”${jdbc.password}” /> 

       </dataSource> 

   </transactionManager> 

    <sqlMap resource=”sql/User.xml” /> 

 

</sqlMapConfig> 

< xml version=”1.0″ encoding=”UTF-8″ >

<!DOCTYPE sqlMapConfig PUBLIC “-//ibatis.apache.org//DTD SQL Map Config 2.0//EN”

“http://ibatis.apache.org/dtd/sql-map-config-2.dtd”>

<sqlMapConfig>

<properties resource=”sqlmap.properties”/>

<transactionManager type=”JDBC”>

<dataSource type=”SIMPLE”>   

<property name=”JDBC.Driver” value=”${jdbc.driverClassName}” />

<property name=”JDBC.ConnectionURL” value=”${jdbc.url}” />

<property name=”JDBC.Username” value=”${jdbc.username}” />

<property name=”JDBC.Password” value=”${jdbc.password}” />

</dataSource>

</transactionManager>

<sqlMap resource=”sql/User.xml” />

</sqlMapConfig>

在这里, 我们把数据库的相关参数保存在了另一个文件中, sqlmap.properties

Java代码 

jdbc.driverClassName=com.mysql.jdbc.Driver  

jdbc.url=jdbc:mysql://localhost:3306/myblog  

jdbc.username=root  

jdbc.password=netjava 

jdbc.driverClassName=com.mysql.jdbc.Driver

jdbc.url=jdbc:mysql://localhost:3306/myblog

jdbc.username=root

jdbc.password=ipanel

这样做的好处, 相信大家也明白..  下次我们再写一个项目的时候, 只需要把这个文件copy 过去, 改掉其中的数据库连接就ok啦 ,  也算是资源的充分利用吧..

至此, 所有的配置文件 都已经上场, 当然上面写的都是最简单的测试, 看起来比较没有那么繁琐, 实际应用时候, 可能最麻烦的地方就是在 配置文件的 sqlmap 的编写…

前面 UserDao.java 的方法中, 有这么一句

Java代码 

1.SqlMapClient sqlMap = Utils.getSqlmap(); 

SqlMapClient sqlMap = Utils.getSqlmap();

Utils 类 就是我们抽取其中的初始化的代码, 单独写成一个类, 当然还是方便重用哈.同时采用的是单实例模式, 相当环保.

  Utils.java

Java代码 

1.public class Utils{  

2.      

3.    private static SqlMapClient sqlMapper;   

4.    public static synchronized SqlMapClient getSqlmap()   

5.    {     

6.          if(sqlMapper==null)   

7.          {   

8.              try {   

9.                  Reader reader = Resources.getResourceAsReader(“SqlMapConfig.xml”);   

10.                  sqlMapper = SqlMapClientBuilder.buildSqlMapClient(reader);   

11.                  reader.close();   

12.                } catch (IOException e) {   

13.                    e.printStackTrace();   

14.                }   

15.          }   

16.            return sqlMapper;   

17.    }   

18.} 

public class Utils{

private static SqlMapClient sqlMapper;

    public static synchronized SqlMapClient getSqlmap()

    {  

          if(sqlMapper==null)

          {

              try {

                  Reader reader = Resources.getResourceAsReader(“SqlMapConfig.xml”);

                  sqlMapper = SqlMapClientBuilder.buildSqlMapClient(reader);

                  reader.close();

                } catch (IOException e) {

                    e.printStackTrace();

                }

          }

            return sqlMapper;

    }

}

好了,  所有的相关文件都已经上场..  当然, 加上 iBATIS的 jar包是前提 , 还是提醒下, 要注意版本问题…

UserDao 是怎样操作数据库的

首先 , Utils 通过SqlMapConfig.xml里面的配置, 连接到数据库, 取得SqlMap , 同时User.xml 将Sql查询映射成java中可以调用的bean, 通过SqlMap 调用这些bean 就是在执行想对应的sql语句…

  • 大小: 23.1 KB

MySql中文乱码解决方案

====================================

        中文乱码解决方案

====================================

 

说明: 在MYSQL中,如果使用缺省的字符集,在建库、建表时,默认使用的是latin1字符集,

 

为ISO 8859-1西欧字符集。插入中文字符时,与之不匹配,就会出现乱码。

 

【解决方案】

 

1. 打开文件: C:\Program Files\MySQL\MySQL Server 5.0\my.ini;

 

2. 将其中所有的default-character-set=latin1改为default-character-set=gb2312,

 

   然后重启MYSQL(以前建立的数据库需重建);

 

   测试: 运行MySQL Command Line Client:

 

         输入show variables like ‘character_set_%’;

 

         可以查看数据库的字符编码如下:

 

 

   mysql> show variables like ‘character_set_%’; 

+————————–+—————————————–+ 

| Variable_name             | Value                                     

+————————–+—————————————–+ 

| character_set_client      | gb2312                                    

| character_set_connection  | gb2312                                   

| character_set_database    | gb2312                                   

| character_set_filesystem  | binary                                    

| character_set_results     | gb2312                                   

| character_set_server      | gb2312                                   

| character_set_system      | utf8                                     

| character_sets_dir        | …… 

+————————–+—————————————–+ 

 

3. 将程序中连接数据库的URL改为(此项非必须):

 

   “jdbc:mysql://localhost:3306/jiyuanpeng useUnicode=true&amp;characterEncoding=gb2312”

Tomcat中数据源的配置及原理

一:数据源介绍 数据源简介

JDBC2.0提供了javax.sql.DataSource的接口,负责与数据库建立连接,实际应用时不需要编写连接数据库代码,可以直接从数据源获得数据库的连接,使得应用于数据库的耦合降低。

 

Dataource中事先建立了多个数据库连接,这些数据库连接保持在数据库连接池中,当程序访问数据库时,只需要从连接池从取出空闲的连接,访问数据库结束,在将这些连接归还给连接池。DataSource对象由容器(Tomcat)提供,不能使用创建实例的方法来生成DataSource对象,要采用JAVA的JNDI(Java Nameing and Directory Interface,java命名和目录接口)来获得DataSource对象的引用。(另有一种说法:“其实从技术上来说,数据源连接方式是不需要目录服务的,我们同样可以通过序列化数据源对象直接访问文件系统。这点是需要明确的。”感兴趣的朋友可以试试。)

 

JNDI是一种将对象和名字绑定的技术,对象工厂负责生产出对象,这些对象都和唯一的名字相绑定。程序中可以通过这个名字来获得对象的引用。Tomcat把DataSource作为一种可配置的JNDI资源来处理,生成DataSource对象的工厂为rg.apache.comm.ons.dbcp.BasicDataSourceFactory。

 

二:配置数据源

配置数据源其实相当简单,可以配置单个应用的数据源,也可以配置整个容器的数据源。以下详细说明如何配置单个应用的数据源。

 

1.准备工作

Tomcat4.1.24 (其它版本也可以,原理相通的) 

确认在%Tomcat _Home%\common\lib下有commons-collections.jar、commons-dbcp.jar、commons-pool.jar包(tomcat默认有这些包),如果没现有,请到此地下载:http://tomcat.apache.org/ 。这三个包是必需的。

 

下载相应数据库驱动,放在%Tomcat _Home%\common\lib下。本例以oracle数据库为例,使用的驱动包为:jdbc14.jar, 数据库为Oracle9i,确认在%Tomcat _Home%\common\lib下有jndi.jar、dbc2_0-stdext.jar(tomcat默认有这些包)。

 

2.配置单个应用的数据源

2.1配置server.xml文件

首先打开%Tomcat _Home%\conf下 server.xml文件,在相应的<Context>中加入<Resource>元素,在<Context>(你的应用配置上下文)中加入以下代码(以MySql为例):

 

 

<Context path="/test" docBase="E:\JAVA\mytest\webapp" > 

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

    <ResourceParams name="jdbc/test"> 

       <parameter> 

           <name>username</name> 

           <value>root</value> 

       </parameter> 

       <parameter> 

           <name>password</name> 

           <value></value> 

       </parameter> 

       <parameter> 

           <name>driverClassName</name> 

           <value>com.mysql.jdbc.Driver</value> 

       </parameter> 

       <parameter> 

           <name>url</name> 

           <value>jdbc:mysql://localhost/dlog</value> 

       </parameter> 

    </ResourceParams> 

</Context>

 

2.2< Resource >配置说明如下:

 

描述

name

指定ResourceJNDI的名字

auth

指定管理ResourceManager,由两个可选值:ContainerApplicationContainer表示由容器来创建和管理ResourceApplication表示由WEB应用来创建和管理Resource。如果在web application deployment descriptor中使用<resource-ref>,这个属性是必需的,如果使用<resource-env-ref>,这个属性是可选的。

type

指定Resource所属的java类名

 

2.3<ResourceParams>元素的属性如下:

 

描述

name

指定ResourceParamsJNDI的名字,必须和Resourcename保持一致

factory

指定生成DataSource对象的factory的类名

maxActive

指定数据库连接池中处于活动状态的数据库连接最大数目,0表示不受限制

maxldle

指定数据库连接池中处于空闲状态的数据库连接的最大数目,0表示不受限制

maxwait

指定数据库连接池中的数据库连接处于空闲状态的最长时间(单位为毫秒),超过这一事件,将会抛出异常。-1表示可以无限期等待。

username

指定连接数据库的用户名

password

指定连接数据库的密码

driverClassName

指定连接数据库的JDBC驱动程序

url

指定连接数据库的URL

 

 

2.3引用数据源

 如果在web应用中访问了由Servlet容器管理的某个JNDI Resource,则必须在web.xml中声明对这个JNDI Resource的引用。表示资源引用的元素为<resource-ref>,该元素加在<wepapp></ wepapp >中。

 打开你的应用配置文件web.xml,输入以下粗体部分:

 <wepapp> ……

<resource-ref>

       <description>connectDB test</description>

       <res-ref-name>jdbc/test</res-ref-name>

       <res-type>javax.sql.DataSource</res-type>

       <res-auth>Container</res-auth>

    </resource-ref>

</ wepapp >

 

2.4<resource-ref>元素的属性如下:

 描述:description  对所引用的资源的说明;
res-ref-name 指定所引用资源的JNDI名字,与<Resource>元素中的name属性保持一致;
res-type  指定所引用资源的类名字,与<Resource>元素中的type属性保持一致;

res-auth  指定所引用资源的Manager,与<Resource>元素中的auth属性保持一致;

 

2.5测试数据源   

 首先,检查Tomcat的%Tomcat _Home%\common\lib下有commons-collections.jar、commons-dbcp.jar、commons-pool.jar包,如果没现有,请到此地下载:http://tomcat.apache.org/    

 注意以上三个包不要引入你的工程类路径,否则可能报错。

 

 然后,将驱动包放入%Tomcat _Home%\common\lib下,注意包必须为.jar后缀。Tomcat只认.jar包。 配置完成后,写个测试,如下:

 

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ page import="java.sql.*"%>
<%@ page import="javax.naming.*"%>
<%@ page import="javax.sql.*"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD 
HTML 4.01 Transitional//EN">
<html>
<head>
</head>
<body>
<%
Context initContext = new InitialContext();
Context envContext = (Context) initContext.lookup("java:/comp/env");
DataSource db = (DataSource)envContext.lookup("jdbc/myoracle ");

//javablogorl为<Resource>元素中name属性的值
Connection conn = db.getConnection( );
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM test");
while(rs.next()){
out.print(rs.getString("admin_name")+" ");
out.print(rs.getString("admin_password")+"<br>");
}
rs.close();
stmt.close();
conn.close(); 

%>
</body>
</html>

 

 如果输出你期望的结果,表示数据源配置成功。

 

3.配置容器全局数据源
以上配置的数据源为单个应用使用的数据源,只能为单个应用所使用,下面我们配置全局的数据源,所有的应用都可以使用,通过引用很自然的使用全局数据源。准备工作同上。

3.1 配置server.xml文件

首先打开%Tomcat _Home%\conf下 server.xml文件,在<GlobalNamingResources>下输入以下粗体部分:

 

<GlobalNamingResources> ……


    <Context path="/test" docBase="E:\JAVA\mytest\webapp" > 

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

    <ResourceParams name="jdbc/test"> 

       <parameter> 

           <name>username</name> 

           <value>root</value> 

       </parameter> 

       <parameter> 

           <name>password</name> 

           <value></value> 

       </parameter> 

       <parameter> 

           <name>driverClassName</name> 

           <value>com.mysql.jdbc.Driver</value> 

       </parameter> 

       <parameter> 

           <name>url</name> 

           <value>jdbc:mysql://localhost/dlog</value> 

           </parameter> 

        </ResourceParams> 

</Context>

</GlobalNamingResources>

 

 

3.2 引用数据源

由于我们配置的是容器全局数据源,因此所有的应用都可以引用这个数据源。在你的应用中建立引用,在<Context></Context>之间输入以下粗体部分:

<Context path="/test" docBase="E:\JAVA\mytest\webapp" >

<ResourceLink name="myDB" global="jdbc/test"  type="javax.sql.DataSource"/>

</Context>

 

3.3 配置应用文件web.xml

打开你的应用配置文件web.xml,输入以下粗体部分:

 

<wepapp> …… 

<resource-ref>

       <description>connectDB test</description>

       <res-ref-name>jdbc/test</res-ref-name>

       <res-type>javax.sql.DataSource</res-type>

       <res-auth>Container</res-auth>

    </resource-ref>

</ wepapp >

 

 3.4测试  创建测试文件:

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ page import="java.sql.*"%>
<%@ page import="javax.naming.*"%>
<%@ page import="javax.sql.*"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD 
HTML 4.01 Transitional//EN">
<html>
<head>
</head>
<body>
<%
Context initContext = new InitialContext();
Context envContext = (Context) initContext.lookup("java:/comp/env");
DataSource db = (DataSource)envContext.lookup("myDB ");//名称与web.xml配置中的一致

//javablogorl为<Resource>元素中name属性的值
Connection conn = db.getConnection( );
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM test");
while(rs.next()){
out.print(rs.getString("admin_name")+" ");
out.print(rs.getString("admin_password")+"<br>");
}
rs.close();
stmt.close();
conn.close();

%>
</body>
</html>

 

 

如果输出你期望的结果,表示数据源配置成功。

Hibernate.cfg.xml文件中删除所有连接数据库的配置参数,添加connection.datasource属性,其中jdbc/test为数据源在应用服务器中的JNDI名:

<property name=”connection.datasource”>java:/comp/env/jdbc/test</property>

 

 

JAVASQL事务

在与数据库操作时,如果执行多条更新的SQL语句(如:update或insert语句),在执行第一条后如果出现异常或电脑断电,

则后面的SQL语句执行不了,这时候设定我们自己提交SQL语句,不让JDBC自动提交,格式为:

conn.setAutoCommit(false);

执行多条SQL语句;

conn.commit();

//恢复自动提交模式

conn.setAutoCommit(true);

代码示例:

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class TestTransaction {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Connection con = null;
		Statement stmt = null;
		ResultSet rs = null;
		PreparedStatement ps = null;
		try {
			Class.forName("com.mysql.jdbc.Driver");
			con = DriverManager.getConnection(
					"jdbc:mysql://localhost:3306/mydb", "root", "root");
			System.out.println("连接数据库成功!");
			stmt = con.createStatement();
			// JAVA默认为TRUE,我们自己处理需要设置为FALSE,并且修改为手动提交,才可以调用rollback()函数
			con.setAutoCommit(false);
			stmt.addBatch("insert into people values(078,'ding','duo')");
			stmt.addBatch("insert into people values(30,'nokia','ddd')");
			stmt.executeBatch();
			// 事务提交
			con.commit();
			// 设置为自动提交,改为TRUE
			con.setAutoCommit(true);

			/*
			 * String sql = "select * from people"; rs = stmt.executeQuery(sql);
			 * while(rs.next()){ System.out.println(rs.getString("id") + " " +
			 * rs.getString("name")); }
			 */
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (SQLException se) {
			se.printStackTrace();
			try {
				// 产生的任何SQL异常都需要进行回滚,并设置为系统默认的提交方式,即为TRUE
				if (con != null) {
					con.rollback();
					con.setAutoCommit(true);
				}
			} catch (SQLException se1) {
				se.printStackTrace();
			}
		} finally {
			try {
				if (rs != null) {
					rs.close();
					rs = null;
				}
				if (stmt != null) {
					stmt.close();
					stmt = null;
				}
				if (con != null) {
					con.close();
					con = null;
				}
			} catch (SQLException se) {
				se.printStackTrace();
			}
		}
	}

}


本文来自CSDN博客,转载请标明出处:http://blog.csdn.net/fafeiboy/archive/2008/07/29/2734889.aspx

 

mysql连接数据库

在程序中引入mysql的驱动包mysql-connector-java-5.0.5-bin.jar

完整的程序如下:
package mysql;

import java.sql.*;

public class MysqlTest {

/**
* @param args
*/
public static void main(String[] args) {
// TODO 自动生成方法存根
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
try {
Class.forName(“com.mysql.jdbc.Driver”);
conn = DriverManager.getConnection(“jdbc:mysql://localhost/test “
+ “user=root&password=520wjb”);
stmt = conn.createStatement();
String str = “Select * from users;”;
rs = stmt.executeQuery(str);
while (rs.next()) {
System.out.println(rs.getInt(1));
System.out.println(rs.getString(2));

}

} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException ex) {
ex.printStackTrace();
System.out.println(“SQLException: ” + ex.getMessage());
System.out.println(“SQLState: ” + ex.getSQLState());
System.out.println(“VendorError: ” + ex.getErrorCode());
} finally {
try {
if (rs != null) {
rs.close();
rs = null;
}

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

if (conn != null) {
conn.close();
conn = null;
}
} catch (SQLException e) {
e.printStackTrace();
}
}

}

}

解决失误导致grails连接mysql错误

"D:\Program Files\Java\jdk1.6.0_14\bin\java" -Xmx256M "-Dgrails.home=D:\Program Files\grails-1.2.0" -Dbase.dir=E:\Progect\java\Intellij\ScheduledTasks "-Dtools.jar=D:\Program Files\Java\jdk1.6.0_14\lib\tools.jar" "-Dgroovy.starter.conf=D:\Program Files\grails-1.2.0/conf/groovy-starter.conf" -Didea.launcher.port=7532 "-Didea.launcher.bin.path=D:\Program Files\JetBrains\IntelliJ IDEA 9.0\bin" -Dfile.encoding=GBK -classpath "D:\Program Files\grails-1.2.0\lib\groovy-all-1.6.7.jar;D:\Program Files\grails-1.2.0\dist\grails-bootstrap-1.2.0.jar;D:\Program Files\JetBrains\IntelliJ IDEA 9.0\lib\idea_rt.jar" com.intellij.rt.execution.application.AppMain org.codehaus.groovy.grails.cli.support.GrailsStarter --main org.codehaus.groovy.grails.cli.GrailsScriptRunner --conf "D:\Program Files\grails-1.2.0/conf/groovy-starter.conf" run-app
Welcome to Grails 1.2.0 - http://grails.org/
Licensed under Apache Standard License 2.0
Grails home is set to: D:\Program Files\grails-1.2.0

Base Directory: E:\Progect\java\Intellij\ScheduledTasks
Resolving dependencies...
Dependencies resolved in 2092ms.
Running script D:\Program Files\grails-1.2.0\scripts\RunApp.groovy
Environment set to development
  [groovyc] Compiling 1 source file to E:\Progect\java\Intellij\ScheduledTasks\target\classes
   [delete] Deleting directory I:\Users\Jeck\.grails\1.2.0\projects\ScheduledTasks\tomcat
Running Grails application..
2010-01-22 09:30:15,597 [main] ERROR context.ContextLoader  - Context initialization failed
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'messageSource': Initialization of bean failed; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'transactionManager': Cannot resolve reference to bean 'sessionFactory' while setting bean property 'sessionFactory'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sessionFactory': Cannot resolve reference to bean 'hibernateProperties' while setting bean property 'hibernateProperties'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'hibernateProperties': Cannot resolve reference to bean 'dialectDetector' while setting bean property 'properties' with key [hibernate.dialect]; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dialectDetector': Invocation of init method failed; nested exception is org.springframework.jdbc.support.MetaDataAccessException: Could not get Connection for extracting meta data; nested exception is org.springframework.jdbc.CannotGetJdbcConnectionException: Could not get JDBC Connection; nested exception is org.apache.commons.dbcp.SQLNestedException: Cannot create PoolableConnectionFactory (Communications link failure

Last packet sent to the server was 0 ms ago.)
 at org.grails.tomcat.TomcatServer.start(TomcatServer.groovy:135)
 at grails.web.container.EmbeddableServer$start.call(Unknown Source)
 at _GrailsRun_groovy$_run_closure5_closure12.doCall(_GrailsRun_groovy:158)
 at _GrailsRun_groovy$_run_closure5_closure12.doCall(_GrailsRun_groovy)
 at _GrailsSettings_groovy$_run_closure10.doCall(_GrailsSettings_groovy:287)
 at _GrailsSettings_groovy$_run_closure10.call(_GrailsSettings_groovy)
 at _GrailsRun_groovy$_run_closure5.doCall(_GrailsRun_groovy:149)
 at _GrailsRun_groovy$_run_closure5.call(_GrailsRun_groovy)
 at _GrailsRun_groovy.runInline(_GrailsRun_groovy:115)
 at _GrailsRun_groovy.this$4$runInline(_GrailsRun_groovy)
 at _GrailsRun_groovy$_run_closure1.doCall(_GrailsRun_groovy:59)
 at RunApp$_run_closure1.doCall(RunApp.groovy:33)
 at gant.Gant$_dispatch_closure4.doCall(Gant.groovy:324)
 at gant.Gant$_dispatch_closure6.doCall(Gant.groovy:334)
 at gant.Gant$_dispatch_closure6.doCall(Gant.groovy)
 at gant.Gant.withBuildListeners(Gant.groovy:344)
 at gant.Gant.this$2$withBuildListeners(Gant.groovy)
 at gant.Gant$this$2$withBuildListeners.callCurrent(Unknown Source)
 at gant.Gant.dispatch(Gant.groovy:334)
 at gant.Gant.this$2$dispatch(Gant.groovy)
 at gant.Gant.invokeMethod(Gant.groovy)
 at gant.Gant.processTargets(Gant.groovy:495)
 at gant.Gant.processTargets(Gant.groovy:480)
 at com.intellij.rt.execution.application.AppMain.main(AppMain.java:110)
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'transactionManager': Cannot resolve reference to bean 'sessionFactory' while setting bean property 'sessionFactory'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sessionFactory': Cannot resolve reference to bean 'hibernateProperties' while setting bean property 'hibernateProperties'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'hibernateProperties': Cannot resolve reference to bean 'dialectDetector' while setting bean property 'properties' with key [hibernate.dialect]; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dialectDetector': Invocation of init method failed; nested exception is org.springframework.jdbc.support.MetaDataAccessException: Could not get Connection for extracting meta data; nested exception is org.springframework.jdbc.CannotGetJdbcConnectionException: Could not get JDBC Connection; nested exception is org.apache.commons.dbcp.SQLNestedException: Cannot create PoolableConnectionFactory (Communications link failure

Last packet sent to the server was 0 ms ago.)
 ... 24 more
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sessionFactory': Cannot resolve reference to bean 'hibernateProperties' while setting bean property 'hibernateProperties'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'hibernateProperties': Cannot resolve reference to bean 'dialectDetector' while setting bean property 'properties' with key [hibernate.dialect]; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dialectDetector': Invocation of init method failed; nested exception is org.springframework.jdbc.support.MetaDataAccessException: Could not get Connection for extracting meta data; nested exception is org.springframework.jdbc.CannotGetJdbcConnectionException: Could not get JDBC Connection; nested exception is org.apache.commons.dbcp.SQLNestedException: Cannot create PoolableConnectionFactory (Communications link failure

Last packet sent to the server was 0 ms ago.)
 ... 24 more
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'hibernateProperties': Cannot resolve reference to bean 'dialectDetector' while setting bean property 'properties' with key [hibernate.dialect]; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dialectDetector': Invocation of init method failed; nested exception is org.springframework.jdbc.support.MetaDataAccessException: Could not get Connection for extracting meta data; nested exception is org.springframework.jdbc.CannotGetJdbcConnectionException: Could not get JDBC Connection; nested exception is org.apache.commons.dbcp.SQLNestedException: Cannot create PoolableConnectionFactory (Communications link failure

Last packet sent to the server was 0 ms ago.)
 ... 24 more
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dialectDetector': Invocation of init method failed; nested exception is org.springframework.jdbc.support.MetaDataAccessException: Could not get Connection for extracting meta data; nested exception is org.springframework.jdbc.CannotGetJdbcConnectionException: Could not get JDBC Connection; nested exception is org.apache.commons.dbcp.SQLNestedException: Cannot create PoolableConnectionFactory (Communications link failure

Last packet sent to the server was 0 ms ago.)
 ... 24 more
Caused by: org.springframework.jdbc.support.MetaDataAccessException: Could not get Connection for extracting meta data; nested exception is org.springframework.jdbc.CannotGetJdbcConnectionException: Could not get JDBC Connection; nested exception is org.apache.commons.dbcp.SQLNestedException: Cannot create PoolableConnectionFactory (Communications link failure

Last packet sent to the server was 0 ms ago.)
 ... 24 more
Caused by: org.springframework.jdbc.CannotGetJdbcConnectionException: Could not get JDBC Connection; nested exception is org.apache.commons.dbcp.SQLNestedException: Cannot create PoolableConnectionFactory (Communications link failure

Last packet sent to the server was 0 ms ago.)
 ... 24 more
Caused by: org.apache.commons.dbcp.SQLNestedException: Cannot create PoolableConnectionFactory (Communications link failure

Last packet sent to the server was 0 ms ago.)
 at org.apache.commons.dbcp.BasicDataSource.createDataSource(BasicDataSource.java:1225)
 at org.apache.commons.dbcp.BasicDataSource.getConnection(BasicDataSource.java:880)
 ... 24 more
Caused by: com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure

Last packet sent to the server was 0 ms ago.
 at com.mysql.jdbc.Util.handleNewInstance(Util.java:406)
 at com.mysql.jdbc.SQLError.createCommunicationsException(SQLError.java:1074)
 at com.mysql.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:2104)
 at com.mysql.jdbc.ConnectionImpl.<init>(ConnectionImpl.java:729)
 at com.mysql.jdbc.JDBC4Connection.<init>(JDBC4Connection.java:46)
 at com.mysql.jdbc.Util.handleNewInstance(Util.java:406)
 at com.mysql.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:302)
 at com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:283)
 at org.apache.commons.dbcp.DriverConnectionFactory.createConnection(DriverConnectionFactory.java:38)
 at org.apache.commons.dbcp.PoolableConnectionFactory.makeObject(PoolableConnectionFactory.java:294)
 at org.apache.commons.dbcp.BasicDataSource.validateConnectionFactory(BasicDataSource.java:1247)
 at org.apache.commons.dbcp.BasicDataSource.createDataSource(BasicDataSource.java:1221)
 ... 25 more
Caused by: java.net.ConnectException: Connection refused: connect
 at java.net.PlainSocketImpl.socketConnect(Native Method)
 at java.net.PlainSocketImpl.doConnect(PlainSocketImpl.java:333)
 at java.net.PlainSocketImpl.connectToAddress(PlainSocketImpl.java:195)
 at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:182)
 at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:366)
 at java.net.Socket.connect(Socket.java:519)
 at java.net.Socket.connect(Socket.java:469)
 at java.net.Socket.<init>(Socket.java:366)
 at java.net.Socket.<init>(Socket.java:209)
 at com.mysql.jdbc.StandardSocketFactory.connect(StandardSocketFactory.java:256)
 at com.mysql.jdbc.MysqlIO.<init>(MysqlIO.java:276)
 at com.mysql.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:2027)
 ... 34 more
2010-01-22 09:30:15,605 [main] ERROR [localhost].[/ScheduledTasks]  - Exception sending context initialized event to listener instance of class org.codehaus.groovy.grails.web.context.GrailsContextLoaderListener
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'messageSource': Initialization of bean failed; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'transactionManager': Cannot resolve reference to bean 'sessionFactory' while setting bean property 'sessionFactory'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sessionFactory': Cannot resolve reference to bean 'hibernateProperties' while setting bean property 'hibernateProperties'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'hibernateProperties': Cannot resolve reference to bean 'dialectDetector' while setting bean property 'properties' with key [hibernate.dialect]; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dialectDetector': Invocation of init method failed; nested exception is org.springframework.jdbc.support.MetaDataAccessException: Could not get Connection for extracting meta data; nested exception is org.springframework.jdbc.CannotGetJdbcConnectionException: Could not get JDBC Connection; nested exception is org.apache.commons.dbcp.SQLNestedException: Cannot create PoolableConnectionFactory (Communications link failure

Last packet sent to the server was 0 ms ago.)
 at org.grails.tomcat.TomcatServer.start(TomcatServer.groovy:135)
 at grails.web.container.EmbeddableServer$start.call(Unknown Source)
 at _GrailsRun_groovy$_run_closure5_closure12.doCall(_GrailsRun_groovy:158)
 at _GrailsRun_groovy$_run_closure5_closure12.doCall(_GrailsRun_groovy)
 at _GrailsSettings_groovy$_run_closure10.doCall(_GrailsSettings_groovy:287)
 at _GrailsSettings_groovy$_run_closure10.call(_GrailsSettings_groovy)
 at _GrailsRun_groovy$_run_closure5.doCall(_GrailsRun_groovy:149)
 at _GrailsRun_groovy$_run_closure5.call(_GrailsRun_groovy)
 at _GrailsRun_groovy.runInline(_GrailsRun_groovy:115)
 at _GrailsRun_groovy.this$4$runInline(_GrailsRun_groovy)
 at _GrailsRun_groovy$_run_closure1.doCall(_GrailsRun_groovy:59)
 at RunApp$_run_closure1.doCall(RunApp.groovy:33)
 at gant.Gant$_dispatch_closure4.doCall(Gant.groovy:324)
 at gant.Gant$_dispatch_closure6.doCall(Gant.groovy:334)
 at gant.Gant$_dispatch_closure6.doCall(Gant.groovy)
 at gant.Gant.withBuildListeners(Gant.groovy:344)
 at gant.Gant.this$2$withBuildListeners(Gant.groovy)
 at gant.Gant$this$2$withBuildListeners.callCurrent(Unknown Source)
 at gant.Gant.dispatch(Gant.groovy:334)
 at gant.Gant.this$2$dispatch(Gant.groovy)
 at gant.Gant.invokeMethod(Gant.groovy)
 at gant.Gant.processTargets(Gant.groovy:495)
 at gant.Gant.processTargets(Gant.groovy:480)
 at com.intellij.rt.execution.application.AppMain.main(AppMain.java:110)
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'transactionManager': Cannot resolve reference to bean 'sessionFactory' while setting bean property 'sessionFactory'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sessionFactory': Cannot resolve reference to bean 'hibernateProperties' while setting bean property 'hibernateProperties'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'hibernateProperties': Cannot resolve reference to bean 'dialectDetector' while setting bean property 'properties' with key [hibernate.dialect]; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dialectDetector': Invocation of init method failed; nested exception is org.springframework.jdbc.support.MetaDataAccessException: Could not get Connection for extracting meta data; nested exception is org.springframework.jdbc.CannotGetJdbcConnectionException: Could not get JDBC Connection; nested exception is org.apache.commons.dbcp.SQLNestedException: Cannot create PoolableConnectionFactory (Communications link failure

Last packet sent to the server was 0 ms ago.)
 ... 24 more
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sessionFactory': Cannot resolve reference to bean 'hibernateProperties' while setting bean property 'hibernateProperties'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'hibernateProperties': Cannot resolve reference to bean 'dialectDetector' while setting bean property 'properties' with key [hibernate.dialect]; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dialectDetector': Invocation of init method failed; nested exception is org.springframework.jdbc.support.MetaDataAccessException: Could not get Connection for extracting meta data; nested exception is org.springframework.jdbc.CannotGetJdbcConnectionException: Could not get JDBC Connection; nested exception is org.apache.commons.dbcp.SQLNestedException: Cannot create PoolableConnectionFactory (Communications link failure

Last packet sent to the server was 0 ms ago.)
 ... 24 more
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'hibernateProperties': Cannot resolve reference to bean 'dialectDetector' while setting bean property 'properties' with key [hibernate.dialect]; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dialectDetector': Invocation of init method failed; nested exception is org.springframework.jdbc.support.MetaDataAccessException: Could not get Connection for extracting meta data; nested exception is org.springframework.jdbc.CannotGetJdbcConnectionException: Could not get JDBC Connection; nested exception is org.apache.commons.dbcp.SQLNestedException: Cannot create PoolableConnectionFactory (Communications link failure

Last packet sent to the server was 0 ms ago.)
 ... 24 more
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dialectDetector': Invocation of init method failed; nested exception is org.springframework.jdbc.support.MetaDataAccessException: Could not get Connection for extracting meta data; nested exception is org.springframework.jdbc.CannotGetJdbcConnectionException: Could not get JDBC Connection; nested exception is org.apache.commons.dbcp.SQLNestedException: Cannot create PoolableConnectionFactory (Communications link failure

Last packet sent to the server was 0 ms ago.)
 ... 24 more
Caused by: org.springframework.jdbc.support.MetaDataAccessException: Could not get Connection for extracting meta data; nested exception is org.springframework.jdbc.CannotGetJdbcConnectionException: Could not get JDBC Connection; nested exception is org.apache.commons.dbcp.SQLNestedException: Cannot create PoolableConnectionFactory (Communications link failure

Last packet sent to the server was 0 ms ago.)
 ... 24 more
Caused by: org.springframework.jdbc.CannotGetJdbcConnectionException: Could not get JDBC Connection; nested exception is org.apache.commons.dbcp.SQLNestedException: Cannot create PoolableConnectionFactory (Communications link failure

Last packet sent to the server was 0 ms ago.)
 ... 24 more
Caused by: org.apache.commons.dbcp.SQLNestedException: Cannot create PoolableConnectionFactory (Communications link failure

Last packet sent to the server was 0 ms ago.)
 at org.apache.commons.dbcp.BasicDataSource.createDataSource(BasicDataSource.java:1225)
 at org.apache.commons.dbcp.BasicDataSource.getConnection(BasicDataSource.java:880)
 ... 24 more
Caused by: com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure

Last packet sent to the server was 0 ms ago.
 at com.mysql.jdbc.Util.handleNewInstance(Util.java:406)
 at com.mysql.jdbc.SQLError.createCommunicationsException(SQLError.java:1074)
 at com.mysql.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:2104)
 at com.mysql.jdbc.ConnectionImpl.<init>(ConnectionImpl.java:729)
 at com.mysql.jdbc.JDBC4Connection.<init>(JDBC4Connection.java:46)
 at com.mysql.jdbc.Util.handleNewInstance(Util.java:406)
 at com.mysql.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:302)
 at com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:283)
 at org.apache.commons.dbcp.DriverConnectionFactory.createConnection(DriverConnectionFactory.java:38)
 at org.apache.commons.dbcp.PoolableConnectionFactory.makeObject(PoolableConnectionFactory.java:294)
 at org.apache.commons.dbcp.BasicDataSource.validateConnectionFactory(BasicDataSource.java:1247)
 at org.apache.commons.dbcp.BasicDataSource.createDataSource(BasicDataSource.java:1221)
 ... 25 more
Caused by: java.net.ConnectException: Connection refused: connect
 at java.net.PlainSocketImpl.socketConnect(Native Method)
 at java.net.PlainSocketImpl.doConnect(PlainSocketImpl.java:333)
 at java.net.PlainSocketImpl.connectToAddress(PlainSocketImpl.java:195)
 at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:182)
 at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:366)
 at java.net.Socket.connect(Socket.java:519)
 at java.net.Socket.connect(Socket.java:469)
 at java.net.Socket.<init>(Socket.java:366)
 at java.net.Socket.<init>(Socket.java:209)
 at com.mysql.jdbc.StandardSocketFactory.connect(StandardSocketFactory.java:256)
 at com.mysql.jdbc.MysqlIO.<init>(MysqlIO.java:276)
 at com.mysql.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:2027)
 ... 34 more
2010-01-22 09:30:15,613 [main] ERROR core.StandardContext  - Error listenerStart
2010-01-22 09:30:15,730 [main] ERROR core.StandardContext  - Context [/ScheduledTasks] startup failed due to previous errors
Server running. Browse to http://localhost:8080/ScheduledTasks

Process finished with exit code 1

 以上是错误的细节部分,引起上述错误的原因是因为在开发模式下,默认的数据库创建模式为create-drop,但是若该成update也不会报错,但是当domain类改变的时候,就汇报上面的错误,原因是domain类与数据库无法对应映射了,解决方法是把update改成create-drop就可以了。

dataSource {
	pooled = true
	driverClassName = "com.mysql.jdbc.Driver"
	username = "root"
	password = "1234"
}
hibernate {
    cache.use_second_level_cache=true
    cache.use_query_cache=true
    cache.provider_class='net.sf.ehcache.hibernate.EhCacheProvider'
}
// environment specific settings
environments {
	development {
		dataSource {
			dbCreate = "create-drop" // one of 'create', 'create-drop','update'  &autoReconnect=true&failOverReadOnly=false
			url = "jdbc:mysql://localhost:3306/scheduledtasks useUnicode=true&characterEncoding=UTF-8"
		}
	}
	test {
		dataSource {
			dbCreate = "update"
			url = "jdbc:hsqldb:mem:testDb"
		}
	}
	production {
		dataSource {
			dbCreate = "update"
			url = "jdbc:hsqldb:file:prodDb;shutdown=true"
		}
	}
}

 

Class.forName和ClassLoader.loadClass的区别

Class.forName和ClassLoader.loadClass的区别

Class.forName和ClassLoader.loadClass的区别技术 :
Class的装载分了三个阶段,loading,linking和initializing,分别定义在The Java Language Specification的12.2,12.3和12.4。
Class.forName(className)实际上是调用Class.forName(className, true, this.getClass().getClassLoader())。注意第二个参数,是指Class被loading后是不是必须被初始化。
ClassLoader.loadClass(className)实际上调用的是ClassLoader.loadClass(name, false),第二个参数指出Class是否被link。
区别就出来了。Class.forName(className)装载的class已经被初始化,而ClassLoader.loadClass(className)装载的class还没有被link。
一般情况下,这两个方法效果一样,都能装载Class。但如果程序依赖于Class是否被初始化,就必须用Class.forName(name)了。
例如,在JDBC编程中,常看到这样的用法,Class.forName(“com.mysql.jdbc.Driver”),如果换成了getClass().getClassLoader().loadClass(“com.mysql.jdbc.Driver”),就不行。
为什么呢?打开com.mysql.jdbc.Driver的源代码看看,
//
// Register ourselves with the DriverManager
//
static {
    try {
        java.sql.DriverManager.registerDriver(new Driver());
    } catch (SQLException E) {
        throw new RuntimeException(“Can’t register driver!”);
    }
}
原来,Driver在static块中会注册自己到java.sql.DriverManager。而static块就是在Class的初始化中被执行。所以这个地方就只能用Class.forName(className)。

除了直接写Class.forName(className)也可以new className,这样也可以执行到static注册驱动程序到DriverManager。

static代码块是在装载的三个过程中的第三个过程执行的,所以说static代码块在代码装载的时候被执行是不严格的,应该说是在装载的第三个阶段被执行的。ClassLoader.loadClass(className)是不完全装载。

Mysql和Tomcat的配置数据库连接池(管理员界面方式)

这几日按照网上现有的教程结合Mysql和Tomcat的配置数据库连接池。费了很大劲终于成功。连接池的配置(Tomcat+MySql)有两种方式:代码配置与可视化配置。
其中,可视化配置方便快捷,下面就根据我配置的经验写下配置的过程。
版本:MySQL-4.19、Tomcat–5.5.9。
在 进行Tomcat连接池配置前,先解压缩mysql-connector-java-xxx.zip,将其中的mysql-connector-java -3.x.x-xxx.jar取出,置于commonlib中,没有?去http://www.mysql.com/products下载吧。

1. 如果Tomcat没有安装Admin,先安装Admin。安装后以admin权限登陆(用户管理在/conf/tomcat-user.xml下,如果没 有admin权限的用户了,新建一个用户,或者将已有的tomcat或者both等设置roles=”admin”);
2.登陆以后,在左边的选择栏里可以看到如下功能:
–Tomcat Server
–+Service (Catalina)
–Resources
–+Data Sources
–+Mail Sessions
–+Environment Entries
–+User Databases
–User Definition
–+Users
–+Groups
–+Roles
点Data Sources–>Data Source Actions 下拉选择Create New Data Source.填写下面几个选项,其中yxz是我建立的mySql实例,根据情况修改。
JNDI Name: mySql/yxz
Data Source URL:jdbc:mysql://localhost:3306/yxz
JDBC Driver Class:com.mysql.jdbc.Driver
User Name:root
Password:root
Max. Active Connections: 20 —最大活跃连接数
Max. Idle Connections:10—最大闲置连接数
Max. Wait for Connection:5000
Validation Query:
完成后,按save,再按Commit Changes,OK!
3.此时,数据库连接池可视化配置完成。但如果要在相应的应用下使用该连接池,仍旧需要另外的工作,就是配置相应的content.xml。在yourapp/META-INF/下建立content.xml文件,将刚才的配置拷贝进去,如下:



factory="org.apache.tomcat.dbcp.dbcp.BasicDataSourceFactory"
driverClassName="com.mysql.jdbc.Driver"
url="jdbc:mysql://localhost:3306/yxz"
username="root" password="root"
maxActive="20" maxIdle="10" maxWait="-1" />


保存,OK。
4. 在mySql里的yxz下建立table:user 进行测试。user表含有字段ID,Name。
5.测试程序,在yourapp下建立index.jsp,拷贝下面代码: