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

JDBC: Introduction to JDBC (Part I)

    博客分类:
  • JDBC
阅读更多

1. JDBC(Java Data Base Connectivity)

        1) Composed with interfaces and classes. Mostly with interfaces as core function and minorly with classes.

        2) It is a part of JavaSE and are basically defined in java.sql and javax.sql package

 

2. Relationships of Application and JDBC API and JDBC Driver and DataBase Connection

jdbc_architecture

    Comment:

        1) Different Databases have different drivers(implementations of interfaces) are offered by database vendor.

        2) Interface Oriented Programming is preferred.

 

3. Steps to connect to DB using JDBC

        1) Register Driver(Only Once is enough through whole application lifecycle)

        2) Build Connection

        3) Create SQL Statement

        4) Execute SQL Statement

        5) Process ResultSet

        6) Release Resource

package edu.xmu.dao.impl;

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

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

public class UserDaoImpl implements UserDao
{
	private String userName = "root";
	private String passWord = "root";
	static
	{
		try
		{
			// 1. Register Driver
			DriverManager.registerDriver(new com.mysql.jdbc.Driver());
		} catch (SQLException e)
		{
			e.printStackTrace();
		}
	}

	@Override
	public void addUser(User user)
	{
		Connection connection = null;
		Statement statement = null;
		String username = user.getUsername();
		String password = user.getPassword();
		String sql = "insert into user(user_name, pass_word) values ('"
				+ username + "', '" + password + "');";
		try
		{
			// 2. Build Connection
			connection = DriverManager.getConnection(
					"jdbc:mysql://localhost:3306/jdbctest", userName, passWord);
			// 3. Create SQL Statement
			statement = connection.createStatement();
			// 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 <= statement.executeUpdate(sql))
			{
				System.out.println("Insert succeed!");
			} else
			{
				System.out.println("Insert failed!");
			}

		} catch (SQLException e)
		{
			e.printStackTrace();
		} finally
		{
			// 6. Release Resources
			// If have resultSet then should also add: resultSet.close();
			try
			{
				statement.close();
			} catch (SQLException e)
			{
				e.printStackTrace();
			} finally
			{
				try
				{
					connection.close();
				} catch (SQLException e)
				{
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
	}

}
    Comments:

        1) Have the risk of SQL-Injection-->Use PreparedStatement instead

        2) The cost of Building Connection is extremely high!

        3) Multiple drivers can be registered in one application or even in a single Class.

package edu.xmu.dao.impl;

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

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

public class UserDaoImpl implements UserDao
{
	private String userName = "root";
	private String passWord = "root";
	static
	{
		try
		{
			// 1. Register Driver
			DriverManager.registerDriver(new com.mysql.jdbc.Driver());
		} catch (SQLException e)
		{
			e.printStackTrace();
		}
	}

	@Override
	public void addUser(User user)
	{
		Connection connection = null;
		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 = DriverManager.getConnection(
					"jdbc:mysql://localhost:3306/jdbctest", userName, passWord);
			// 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
			// If have resultSet then should also add: resultSet.close();
			try
			{
				preparedStatement.close();
			} catch (SQLException e)
			{
				e.printStackTrace();
			} finally
			{
				try
				{
					connection.close();
				} catch (SQLException e)
				{
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
	}

}
package edu.xmu.dao.impl;

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

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

public class UserDaoImpl implements UserDao
{
        //Connection pool can be used!
	private static String userName = "root";
	private static String passWord = "root";
	private static Connection connection = null;
	static
	{
		try
		{
			// 1. Register Driver
			DriverManager.registerDriver(new com.mysql.jdbc.Driver());
                        // 2. Build Connection
			connection = DriverManager.getConnection(
					"jdbc:mysql://localhost:3306/jdbctest", userName, passWord);
		} catch (SQLException e)
		{
			e.printStackTrace();
		}
	}

	@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
		{
			// 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
			// If have resultSet then should also add: resultSet.close();
			try
			{
				preparedStatement.close();
			} catch (SQLException e)
			{
				e.printStackTrace();
			}
		}
	}

	@Override
	public User getUser(int id)
	{
		// TODO Auto-generated method stub
		PreparedStatement preparedStatement = null;
		ResultSet resultSet = null;
		User user = new User();
		String sql = "select id, user_name, pass_word from user where id = ?";
		try
		{
			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)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally
		{
			try
			{
				resultSet.close();
				preparedStatement.close();
			} catch (SQLException e)
			{
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return user;
	}

}

 

1. Driver Register (Three ways)

    1) DriverManager.registerDriver(new com.mysql.jdbc.Driver());

            ---> There is a driverList in DriverManager.

            ---> DriverManager.getConnection(URL) will make the DriverManager traverse driverList for

                   resolving this URL and create connection.

    2) System.setProperty("jdbc.drivers", "com.mysql.jdbc.Driver:com.oracle.jdbc.Driver");

            ---> Use ":" as seperator for multiple Driver Register

    3) Class.forName("com.mysql.jdbc.Driver");

            ---> Just load com.mysql.jdbc.Driver into JVM. And havn't created any instance of this Driver

            ---> How/When did they register this Driver into DriverManager(Put this driver into driverList)?


            ---> When  Class.forName("com.mysql.jdbc.Driver") is executed, com.mysql.jdbc.Driver extends Driver, so the static {java.sql.DriverManager.registerDriver(new Driver());} will execute. The driver itself will be added into the driverList.

    Comment:

            1) The third method is prefered.

                 Because when using DriverManager.registerDriver(new com.mysql.jdbc.Driver(...));

                 The new com.mysql.jdbc.Driver() will execute static{java.sql.DriverManager.registerDriver(...)}

                 And then we use DriverManager.registerDriver(...); will cause register the same dirver again.

            2) The third method is prefered.

                 Because when using DriverManager.registerDriver(new com.mysql.jdbc.Driver(...));

                 This statement will make this class depend on the com.mysql.jdbc.Driver class and violate AOP.

                 The second and third method will not violate AOP because the app depends on String/Config.

                 The program will run successfully when we don't have the mysql jdbc driver when using 2nd or 3rd way. And will not proceed successfully when using 1st way.

try
		{
			// 1. Register Driver
			Class.forName("com.mysql.jdbc.Driver");
			connection = DriverManager.getConnection(
					"jdbc:mysql://localhost:3306/jdbctest", userName, passWord);
		} catch (SQLException e)
		{
			e.printStackTrace();
		} catch (ClassNotFoundException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

 

2. Build Connection

private static Connection connection = null;
connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/jdbctest", userName, passWord);

    1) URL Format:

          1) jdbc:subProtocol:subName://hostName:portnumber/databasename?propertyName=propertyValue&propertyName=propertyValue

          2) user, password can set as user=username&password=password as key-value in URL

          3) Other prarams: useUnicode=true&characterEncoding=GBK

    2) Don't forget close connection after used.-->Best Practice: Build connection as late as possible and close connection as early as possible.

  • 大小: 22.1 KB
分享到:
评论

相关推荐

    《Pearson.Java.How.To.Program.late.objects.version.10th.Edition》 高清完整英文PDF版

    Chapter 1 Introduction to Computers, the Internet and Java Chapter 2 Introduction to Java Applications; Input/Output and Operators Chapter 3 Control Statements: Part 1; Assignment, ++ and -- Operators...

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

    Part I - Introduction Chapter 1 - What Is MySQL? Chapter 2 - The Test Environment Chapter 3 - Introductory Example (An Opinion Poll) Part II - Fundamentals Chapter 4 - User Interfaces ...

    Advanced.Java.Programming.0199455503

    Advanced Java Programming is a textbook specially designed for undergraduate and postgraduate students of Computer Science, ... Introduction to J2EE Chapter 27. Java and CORBA 28. Java Server Faces

    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. ...

    The Definitive Guide to Jython - Python for the Java Platform (2010).pdf

    Part I: Jython Basics: Learning the Language....................................................................................1 ■ Chapter 1: Language and Syntax.......................................

    Mahout in Action

    7 ■ Introduction to clustering 117 8 ■ Representing data 130 9 ■ Clustering algorithms in Mahout 145 10 ■ Evaluating and improving clustering quality 184 11 ■ Taking clustering to production 198 ...

    MySql存储过程编程.chm

    Part I: Stored Programming Fundamentals Chapter 1. Introduction to MySQL Stored Programs Section 1.1. What Is a Stored Program? Section 1.2. A Quick Tour Section 1.3. Resources for Developers...

    Spring中文帮助文档

    I. 核心技术 3. IoC(控制反转)容器 3.1. 简介 3.2. 基本原理 - 容器和bean 3.2.1. 容器 3.2.2. 实例化容器 3.2.3. 多种bean 3.2.4. 使用容器 3.3. 依赖 3.3.1. 注入依赖 3.3.2. 依赖配置详解 3.3.3. 使用...

    Spring API

    I. 核心技术 3. IoC(控制反转)容器 3.1. 简介 3.2. 基本原理 - 容器和bean 3.2.1. 容器 3.2.2. 实例化容器 3.2.3. 多种bean 3.2.4. 使用容器 3.3. 依赖 3.3.1. 注入依赖 3.3.2. 依赖配置详解 3.3.3. 使用...

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

    I. 核心技术 3. 控制反转容器 3.1. 简介 3.2. 容器和bean的基本原理 3.2.1. 容器 3.2.1.1. 配置元数据 3.2.2. 实例化容器 3.2.2.1. 组成基于XML配置元数据 3.2.3. 多种bean 3.2.3.1. 命名bean 3.2.3.2. 实例化bean ...

    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 开发参考手册

    I. 核心技术 3. 控制反转容器 3.1. 简介 3.2. 容器和bean的基本原理 3.2.1. 容器 3.2.2. 实例化容器 3.2.3. 多种bean 3.2.4. 使用容器 3.3. 依赖 3.3.1. 注入依赖 3.3.2. 构造器参数的解析 3.3.3. bean...

    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 .........................................................................

    postGIS 用户手册

    1 Introduction 1 1.1 Project Steering Committee . . . . . . . . . . . . . . . . . . . . . . . . . . 1 1.2 Contributors Past and Present . . . . . . . . . . . . . . . 1 1.3 More Information . . . . . ....

    hibernate3.6 文档(pdf 格式)

    3.3. JDBC connections ............................................................................................ 32 3.4. Optional configuration properties ..............................................

Global site tag (gtag.js) - Google Analytics