---
title: "Servlet + JavaBean连接数据库"
author: "txazo"
date: "2012-09-01T09:31:08Z"
tags: []
categories: ["编程语言"]
slug: "servlet-javabean"
draft: false
lastmod: "2012-09-02T09:14:53Z"
id: 1669205
url: "https://txazo.iteye.com/blog/1669205"
---

1. JDBC连接数据库
2. C3P0连接数据库
3. DBCP连接数据库
4. Tomcat数据源
5. JBoss数据源
6. WebLogic数据源
7. Connection操作数据库
8. JDBC事务处理
9. Tomcat JTA
10. JBoss JTA
11. WebLogic JTA

1. JDBC连接数据库
直接使用JDBC API获得Connection连接。

```java

public class ConnectionUtil {

	private static final String DRIVER = "com.mysql.jdbc.Driver";
	private static final String URL = "jdbc:mysql://127.0.0.1:3306/txazo";
	private static final String USER = "root";
	private static final String PASSWORD = "root";

	static {
		try {
			Class.forName(DRIVER);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	private ConnectionUtil() {
	}

	public static synchronized Connection getConnection() {
		Connection connection = null;
		try {
			connection = DriverManager.getConnection(URL, USER, PASSWORD);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return connection;
	}

}

```

2. C3P0连接数据库
C3P0连接池。

```java

public class ConnectionUtil {

	private static ComboPooledDataSource dataSource = null;

	static {
		try {
			dataSource = new ComboPooledDataSource();
			dataSource.setDriverClass("com.mysql.jdbc.Driver");
			dataSource.setJdbcUrl("jdbc:mysql://127.0.0.1/txazo");
			dataSource.setUser("root");
			dataSource.setPassword("root");
            dataSource.setMinPoolSize(2);
			dataSource.setMaxPoolSize(20);
			dataSource.setInitialPoolSize(4);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private ConnectionUtil() {
	}

	public static synchronized Connection getConnection() {
		Connection connection = null;
		try {
			connection = dataSource.getConnection();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return connection;
	}

}

```

3. DBCP连接数据库
DBCP连接池。

```java

public class ConnectionUtil {

	private static BasicDataSource dataSource = null;

	static {
		dataSource = new BasicDataSource();
		dataSource.setDriverClassName("com.mysql.jdbc.Driver");
		dataSource.setUrl("jdbc:mysql://127.0.0.1/txazo");
		dataSource.setUsername("root");
		dataSource.setPassword("root");
		dataSource.setMaxActive(20);
		dataSource.setInitialSize(4);
	}

	private ConnectionUtil() {
	}

	public static synchronized Connection getConnection() {
		Connection connection = null;
		try {
			connection = dataSource.getConnection();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return connection;
	}

}

```

4. Tomcat数据源
1)TOMCAT_HOME/conf/context.xml的<Context>节点下添加如下内容：

```xml

<Resource name="jdbc/txazo" auth="Container" type="javax.sql.DataSource"
    maxActive="100" maxIdle="30" maxWait="10000"
    username="root" password="root" driverClassName="com.mysql.jdbc.Driver"
    url="jdbc:mysql://localhost:3306/txazo"/>

```

2)WEB-INF/web.xml中添加如下内容：

```xml

<resource-ref>
    <res-ref-name>jdbc/txazo</res-ref-name>
    <res-type>javax.sql.DataSource</res-type>
    <res-auth>Container</res-auth>
</resource-ref>

```

3)Connection连接工具类

```java

public class ConnectionUtil {

	private static DataSource dataSource = null;

	static {
		Context context = null;
		try {
			context = new InitialContext();
			dataSource = (DataSource) context
					.lookup("java:comp/env/jdbc/txazo");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	private ConnectionUtil() {
	}

	public static synchronized Connection getConnection() {
		Connection connection = null;
		try {
			connection = dataSource.getConnection();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return connection;
	}

}

```

5. JBoss数据源
1)配置数据源
JBOSS_HOME/docs/examples/jca/mysql-ds.xml复制到JBOSS_HOME/server/default/deploy下，重命名为txazo-ds.xml，并修改内容如下：

```xml

<?xml version="1.0" encoding="UTF-8"?>

<datasources>
  <local-tx-datasource>
    <jndi-name>txazo</jndi-name>
    <connection-url>jdbc:mysql://127.0.0.1:3306/txazo</connection-url>
    <driver-class>com.mysql.jdbc.Driver</driver-class>
    <user-name>root</user-name>
    <password>root</password>
    <exception-sorter-class-name>
        org.jboss.resource.adapter.jdbc.vendor.MySQLExceptionSorter
    </exception-sorter-class-name>
    <metadata>
       <type-mapping>mySQL</type-mapping>
    </metadata>
  </local-tx-datasource>
</datasources>

```

2)Connection连接工具类

```java

public class ConnectionUtil {

	private static DataSource dataSource = null;

	static {
		Context context = null;
		try {
			context = new InitialContext();
			dataSource = (DataSource) context.lookup("java:/txazo");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private ConnectionUtil() {
	}

	public static synchronized Connection getConnection() {
		Connection connection = null;
		try {
			connection = dataSource.getConnection();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return connection;
	}

}

```

6. WebLogic数据源
1)配置数据源
使用WebLogic控制台配置数据源txazo。
2)Connection连接工具类

```java

public class ConnectionUtil {

	private static DataSource dataSource = null;

	static {
		Context context = null;
		try {
			context = new InitialContext();
			dataSource = (DataSource) context.lookup("txazo");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private ConnectionUtil() {
	}

	public static synchronized Connection getConnection() {
		Connection connection = null;
		try {
			connection = dataSource.getConnection();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return connection;
	}

}

```

7. Connection操作数据库
1)增删改操作

```java

Connection connection = null;
PreparedStatement statement = null;

try {
    connection = ConnectionUtil.getConnection();
    statement = connection.prepareStatement("delete from user");
    statement.executeUpdate();
} catch (Exception e) {
    e.printStackTrace();
} finally {
    try {
        if (statement != null) {
            statement.close();
        }
        if (connection != null) {
            connection.close();
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

```

2)查询操作

```java

Connection connection = null;
PreparedStatement statement = null;
ResultSet resultSet = null;

try {
    connection = ConnectionUtil.getConnection();
    statement = connection.prepareStatement("select * from user");
    resultSet = statement.executeQuery();
    while (resultSet.next()) {
    }
} catch (Exception e) {
    e.printStackTrace();
} finally {
    try {
        if (resultSet != null) {
            resultSet.close();
        }
        if (statement != null) {
            statement.close();
        }
        if (connection != null) {
            connection.close();
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

```

8. JDBC事务处理

```java

Connection connection = null;
PreparedStatement statement = null;

try {
    connection = ConnectionUtil.getConnection();
    connection.setAutoCommit(false);
    statement = connection.prepareStatement("delete from user");
    statement.executeUpdate();
    connection.commit();
} catch (Exception e) {
    e.printStackTrace();
　　try {
        connection.rollback();
    } catch (Exception exception) {
        exception.printStackTrace();
    }
} finally {
    try {
        if (statement != null) {
            statement.close();
        }
        if (connection != null) {
            connection.close();
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

```

9. Tomcat JTA
1)下载JTOM，添加相应Jar包到TOMCAT_HOME/lib下。
2)TOMCAT_HOME/lib/carol.properties：

```java

carol.protocols=jrmp
carol.jvm.rmi.local.call=true
carol.start.jndi=false
carol.start.ns=false
carol.jndi.java.naming.factory.url.pkgs=org.apache.naming

```

3)TOMCAT_HOME/conf/context.xml的<Context>节点下添加如下内容：

```xml

<Resource name="jdbc/txazo" auth="Container" type="javax.sql.DataSource"
    factory="org.objectweb.jotm.datasource.DataSourceFactory"
    maxActive="100" maxIdle="30" maxWait="10000"
    username="root" password="root" driverClassName="com.mysql.jdbc.Driver"
    url="jdbc:mysql://localhost:3306/txazo"/>
			   
<Resource name="UserTransaction" 
    auth="Container" 
    type="javax.transaction.UserTransaction" />

<Transaction factory="org.objectweb.jotm.UserTransactionFactory" 
    jotm.timeout="60" />

```

4)JTA编程事务

```java

UserTransaction transaction = null;
Connection connection = null;
PreparedStatement statement = null;

try {
    Context context = new InitialContext();
    transaction = (UserTransaction) context.lookup("java:comp/UserTransaction");
    transaction.begin();

    connection = ConnectionUtil.getConnection();
    connection.setAutoCommit(false);
    statement = connection.prepareStatement("delete from user");
    statement.executeUpdate();

    transaction.commit();
} catch (Exception e) {
    e.printStackTrace();
　　try {
        transaction.rollback();
    } catch (Exception exception) {
        exception.printStackTrace();
    }
} finally {
    try {
        if (statement != null) {
            statement.close();
        }
        if (connection != null) {
            connection.close();
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

```

10. JBoss JTA
JBoss中JTA事务管理器的JNDI名为UserTransaction。

```java

UserTransaction transaction = null;
Connection connection = null;
PreparedStatement statement = null;

try {
    Context context = new InitialContext();
    transaction = (UserTransaction) context.lookup("UserTransaction");
    transaction.begin();

    connection = ConnectionUtil.getConnection();
    connection.setAutoCommit(false);
    statement = connection.prepareStatement("delete from user");
    statement.executeUpdate();

    transaction.commit();
} catch (Exception e) {
    e.printStackTrace();
　　try {
        transaction.rollback();
    } catch (Exception exception) {
        exception.printStackTrace();
    }
} finally {
    try {
        if (statement != null) {
            statement.close();
        }
        if (connection != null) {
            connection.close();
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

```

11. WebLogic JTA
WebLogic中JTA事务管理器的JNDI名为javax.transaction.UserTransaction。

```java

UserTransaction transaction = null;
Connection connection = null;
PreparedStatement statement = null;

try {
    Context context = new InitialContext();
    transaction = (UserTransaction) context
        .lookup("javax.transaction.UserTransaction");
    transaction.begin();

    connection = ConnectionUtil.getConnection();
    connection.setAutoCommit(false);
    statement = connection.prepareStatement("delete from user");
    statement.executeUpdate();

    transaction.commit();
} catch (Exception e) {
    e.printStackTrace();
　　try {
        transaction.rollback();
    } catch (Exception exception) {
        exception.printStackTrace();
    }
} finally {
    try {
        if (statement != null) {
            statement.close();
        }
        if (connection != null) {
            connection.close();
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

```