`
DavyJones2010
  • 浏览: 155052 次
  • 性别: Icon_minigender_1
  • 来自: 杭州
社区版块
存档分类
最新评论

JDBC: Introduction to JDBC (Part II)

    博客分类:
  • JDBC
阅读更多

1. Good Practice: 

        1>Build Connection as late as possible.

        2>Close Connection as earyl as possible.

        3>Connection Pool can be used to enhance performance.

 

2. Good Example:

 

        1> JdbcUtil.java

package utils;

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


public final class JdbcUtil
{
	// Trying to make all secret filed as private.
	private static String url = "jdbc:mysql://localhost:3306/jdbctest";
	private static String username = "root";
	private static String password = "root";
	// Enable to make sure driver is only registered once.
	static
	{
		try
		{
			Class.forName("com.mysql.jdbc.Driver");
		} catch (ClassNotFoundException e)
		{
			e.printStackTrace();
		}
	}
	
	// Disable user to instantiate JdbcUtil
	private JdbcUtil()
	{
	}
	public static Connection getConnection() throws SQLException
	{
		return DriverManager.getConnection(url, username, password);
	}
	// Have to judge if a certain field is null
	public static void releaseResource(ResultSet resultSet,
			Statement statement, Connection connection)
	{

		try
		{
			if (null != resultSet)
			{
				resultSet.close();
			}
		} catch (SQLException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally
		{
			try
			{
				if (null != statement)
				{
					statement.close();
				}
			} catch (SQLException e)
			{
				// TODO Auto-generated catch block
				e.printStackTrace();
			} finally
			{
				try
				{
					if (null != connection)
					{
						connection.close();
					}
				} catch (SQLException e)
				{
					e.printStackTrace();
				}
			}
		}
	}
}

 

        2>UserDaoImpl.java

package edu.xmu.dao.impl;

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

import utils.JdbcUtil;

import edu.xmu.dao.UserDao;
import edu.xmu.domain.User;

public class UserDaoImpl implements UserDao
{
	private static Connection connection = null;

	@Override
	public void addUser(User user)
	{
		PreparedStatement preparedStatement = null;
		String username = user.getUsername();
		String password = user.getPassword();
		String sql = "insert into user(user_name, pass_word) values (?, ?)";
		try
		{
			// 2. Build Connection
			connection = JdbcUtil.getConnection();
			// 3. Create SQL Statement
			preparedStatement = connection.prepareStatement(sql);
			preparedStatement.setString(1, username);
			preparedStatement.setString(2, password);

			// 4. Execute SQL Statement
			// 5. If statement is C/U/D, returns integer value indicating rows
			// affected
			// If statement is R, returns result set.
			if (0 <= preparedStatement.executeUpdate())
			{
				System.out.println("Insert succeed!");
			} else
			{
				System.out.println("Insert failed!");
			}

		} catch (SQLException e)
		{
			e.printStackTrace();
		} finally
		{
			// 6. Release Resources
			JdbcUtil.releaseResource(null, preparedStatement, connection);
		}
	}

	@Override
	public User getUser(int id)
	{
		PreparedStatement preparedStatement = null;
		ResultSet resultSet = null;
		User user = new User();
		String sql = "select id, user_name, pass_word from user where id = ?";
		try
		{
			connection = JdbcUtil.getConnection();
			preparedStatement = connection.prepareStatement(sql);

			preparedStatement.setInt(1, id);

			resultSet = preparedStatement.executeQuery();

			while (resultSet.next())
			{
				user.setId(id);
				user.setUsername(resultSet.getString("user_name"));
				user.setPassword(resultSet.getString("pass_word"));
			}
		} catch (SQLException e)
		{
			e.printStackTrace();
		} finally
		{
			JdbcUtil.releaseResource(resultSet, preparedStatement, connection);
		}
		return user;
	}
}

 

分享到:
评论

相关推荐

    APress - The Definitive Guide to MySQL, 2nd Ed - 2004 - (By Laxxuss).chm

    Part II - Fundamentals Chapter 4 - User Interfaces Chapter 5 - Database Design Chapter 6 - An Introduction to SQL Chapter 7 - SQL Recipes Chapter 8 - InnoDB Tables and Transactions ...

    hibernate_reference.pdf

    #### Introduction to Hibernate Hibernate is an Object-Relational Mapping (ORM) solution for Java applications that provides a powerful framework for mapping object-oriented domain models to ...

    Hibernate Reference Documentation3.1

    1. Introduction to Hibernate 1.1. Preface 1.2. Part 1 - The first Hibernate Application 1.2.1. The first class 1.2.2. The mapping file 1.2.3. Hibernate configuration 1.2.4. Building with Ant 1.2.5. ...

    geronimo-book.pdf

    - **Selected APIs and Tools:** Geronimo leverages various APIs and tools to enhance its capabilities, such as JMS, JDBC, and others. #### Acquiring and Quick Start Guide for Geronimo To get started ...

    MySql存储过程编程.chm

    Part II: Stored Program Construction Chapter 7. Creating and Maintaining Stored Programs Section 7.1. Creating Stored Programs Section 7.2. Editing an Existing Stored Program Section 7.3. SQL...

    Spring中文帮助文档

    II. 中间层数据访问 9. 事务管理 9.1. 简介 9.2. 动机 9.3. 关键抽象 9.4. 使用资源同步的事务 9.4.1. 高层次方案 9.4.2. 低层次方案 9.4.3. TransactionAwareDataSourceProxy 9.5. 声明式事务管理 9.5.1....

    Spring API

    II. 中间层数据访问 9. 事务管理 9.1. 简介 9.2. 动机 9.3. 关键抽象 9.4. 使用资源同步的事务 9.4.1. 高层次方案 9.4.2. 低层次方案 9.4.3. TransactionAwareDataSourceProxy 9.5. 声明式事务管理 9.5.1....

    Spring-Reference_zh_CN(Spring中文参考手册)

    II. 中间层数据访问 9. 事务管理 9.1. 简介 9.2. 动机 9.3. 关键抽象 9.4. 使用资源同步的事务 9.4.1. 高层次方案 9.4.2. 低层次方案 9.4.3. TransactionAwareDataSourceProxy 9.5. 声明式事务管理 9.5.1. 理解...

    spring chm文档

    Copies of this document may be made for your own use and for distribution to others, provided that you do not charge any fee for such copies and further provided that each copy contains this Copyright...

    Spring 2.0 开发参考手册

    II. 中间层数据访问 9. 事务管理 9.1. 简介 9.2. 动机 9.3. 关键抽象 9.4. 使用资源同步的事务 9.4.1. 高层次方案 9.4.2. 低层次方案 9.4.3. TransactionAwareDataSourceProxy 9.5. 声明式事务管理 9.5.1....

    spring-framework-reference4.1.4

    4.1. Introduction to the Spring IoC container and beans .............................................. 22 4.2. Container overview .........................................................................

    spring-framework-reference-4.1.2

    4.1. Introduction to the Spring IoC container and beans .............................................. 22 4.2. Container overview .........................................................................

Global site tag (gtag.js) - Google Analytics