java jdbc连接数据库(使用mysql进行连接)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/j086924/article/details/51546876

一、JDBC简介

Java 数据库连接,(Java Database Connectivity,简称JDBC)是Java语言中用来规范客户端程序如何来访问数据库的应用程序接口,提供了诸如查询和更新数据库中数据的方法。JDBC也是Sun Microsystems的商标。它JDBC是面向关系型数据库的。

1、JDBC架构:
JDBC API支持两层和三层处理模型进行数据库访问,但在一般的JDBC体系结构由两层组成:

JDBC API: 提供了应用程序对JDBC的管理连接;

JDBC Driver API: 支持JDBC管理到驱动器连接;

JDBC API的使用驱动程序管理器和数据库特定的驱动程序提供透明的连接到异构数据库;

JDBC驱动程序管理器可确保正确的驱动程序来访问每个数据源,该驱动程序管理器能够支持连接到多个异构数据库的多个并发的驱动程序;

以下是结构图,它显示了驱动程序管理器方面的JDBC驱动程序和Java应用程序的位置:


2、常见的JDBC组件:
JDBC API提供了以下接口和类:

DriverManager: 这个类管理数据库驱动程序的列表,内容是否符合从Java应用程序使用的通信子协议正确的数据库驱动程序的连接请求,识别JDBC在一定子协议的第一个驱动器将被用来建立数据库连接;

Driver: 此接口处理与数据库服务器通信,很少直接与驱动程序对象,相反,使用DriverManager中的对象,它管理此类型的对象,它也抽象与驱动程序对象工作相关的详细信息;

Connection : 此接口与接触数据库的所有方法,连接对象表示通信上下文,即,与数据库中的所有的通信是通过唯一的连接对象;

Statement : 可以使用这个接口创建的对象的SQL语句提交到数据库,一些派生的接口接受除执行存储过程的参数;

ResultSet: 这些对象保存从数据库后,执行使用Statement对象的SQL查询中检索数据,它作为一个迭代器,让您可以通过移动它的数据;

SQLException: 这个类处理发生在一个数据库应用程序的任何错误.

二、连接JDBC需要掌握的基本知识

1、数据库的基本操作,

eg:Mysql的安装和基本操作(insert,delete,update,query)

2、java开发工具的使用,

eg:Eclipse/MyEclipse (包括mysql-connector-java-5.0.3-bin.jar的导入)

三、JDBC的连接及代码演示

1、JDBC连接工具类

1)、Configuration.java:可以从.xml文件中连接数据库的配置信息,需要引入dom4j-1.6.1.jar包

package cn.java.jdbc;

import java.io.InputStream;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

public class Configuration {
	
	private String url;
	private String driver;
	private String username;
	private String password;

	public Configuration() {
	}
	
	public Configuration(String url, String driver, String username,
			String password) {
		super();
		this.url = url;
		this.driver = driver;
		this.username = username;
		this.password = password;
	}
	
	public static Configuration getConfigure()
	{
		
		try {
			InputStream in = Configuration.class.getResourceAsStream("/db.xml");
			if (null!=in) {
				return load(in);
			}
			return null;
		} catch (DocumentException e) {
			e.printStackTrace();
			return null;
		}
		
	}

	private static Configuration load(InputStream in) throws DocumentException {
		SAXReader reader = new SAXReader();
		Document doc = reader.read(in);
		Element jdbc = doc.getRootElement();
		String url = jdbc.element("url").getText();
		String driver = jdbc.element("driver").getText();
		String username = jdbc.element("username").getText();
		String password = jdbc.element("password").getText();
		Configuration cfg = new Configuration(url, driver, username, password);
		return cfg;
	}

	public String getUrl() {
		return url;
	}

	public void setUrl(String url) {
		this.url = url;
	}

	public String getDriver() {
		return driver;
	}

	public void setDriver(String driver) {
		this.driver = driver;
	}

	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}


}


2)、db.xml:保存数据库的配置信息

<?xml version="1.0" encoding="UTF-8"?>
<jdbc>
<url>jdbc:mysql://localhost:3306/test</url>
<driver>com.mysql.jdbc.Driver</driver>
<username>root</username>
<password></password>
</jdbc>


3)、ConnectionFactory.java:JDBC连接工厂方法之一

package cn.java.jdbc;

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

public class ConnectionFactory {
	
	private static ConnectionFactory connectionFactory=null;
	private static Configuration config=Configuration.getConfigure();
	
    private ConnectionFactory()
    {
		try {
		Class.forName(config.getDriver());
	} catch (ClassNotFoundException e) {
	}
    }
    
    public Connection getConnection() throws SQLException
    {
    	
    	Connection con=null;
    	try {
			con=DriverManager.getConnection(config.getUrl(), config.getUsername(), config.getPassword());
			
			return con;
		}finally{
			
//			if (null != con) {
//				con.close();
//			}
		}
    	
    }
    
    public static ConnectionFactory getInstance()
    {  
    	if (null==connectionFactory) {
    		connectionFactory=new ConnectionFactory();
		}
    	
		return connectionFactory;
    	
    }

}

4)、ConnectionFactory2.java:JDBC连接工厂方法之二

package cn.java.jdbc;

import java.sql.Connection;
import java.sql.SQLException;

import javax.sql.DataSource;

import com.mysql.jdbc.jdbc2.optional.MysqlDataSource;

public class ConnectionFactory2 {


	private DataSource ds ;

	private static ConnectionFactory2 connectionFactory2 = null;

	private ConnectionFactory2() {
		
		MysqlDataSource myDS = new MysqlDataSource() ;
		myDS.setServerName("localhost");
		myDS.setDatabaseName("test");
		myDS.setPort(3306) ;
		myDS.setUser("root");
		myDS.setCharacterEncoding("utf-8");
		myDS.setPassword("");
		this.ds = myDS ;
	}

	public Connection getConnection() throws SQLException {

		Connection conn = null;
		try {
			conn = ds.getConnection() ;
			conn.setAutoCommit(false);
			return conn;
		} catch (SQLException e) {
			if (null != conn) {
				conn.close();
			}
			throw e;
		}
	}

	public static ConnectionFactory2 getInstance() {

		if (null == connectionFactory2) {
			connectionFactory2 = new ConnectionFactory2();
		}
		return connectionFactory2;

	}

}

5)、User.java:定义数据库表user中的id和name的bean类,其中id是自动增长的

package cn.java.jdbc;

public class User {
	private int id;
	private String name;
	
	public User() {
	}
	public User(int id, String name) {
		this.id = id;
		this.name = name;
	}

	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}
	

}

6)、UserDao.java:user表的操作类,实现了insert、delete、update、query等方法

package cn.java.jdbc;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class UserDao {
	private PreparedStatement st = null;
	private ResultSet rs = null;
	
	public UserDao() {
	}
	
	public void insert(	Connection con,String name) throws SQLException,IOException {
		String sql="insert into user(name) values(?) ";
		try{
			st=con.prepareStatement(sql);
			st.setString(1, name);
			st.executeUpdate();
		}finally{
			if (null!=st) {
				st.close();
			}
			
		}
		
	}
	
	public void delete(Connection con,int id) throws SQLException,IOException {
		String sql="delete from user where id=?";
		try{
			st=con.prepareStatement(sql);
			st.setInt(1, id);
			st.executeUpdate();
		}finally{
			if (null!=st) {
				st.close();
			}
			
		}
	}
	
	public void update(	Connection con,int id,String name) throws SQLException,IOException {
		String sql="update user set name=? where id=?";
		
		try{
			st=con.prepareStatement(sql);
			st.setString(1, name);
			st.setInt(2, id);
			st.executeUpdate();
		}finally{
			if (null!=st) {
				st.close();
			}
		}

	}
	
	public User query(Connection con,int index) throws SQLException,IOException{
		User user=new User();
		String sql="select * from user where id=?";
		try{
			st=con.prepareStatement(sql);
			st.setInt(1, index);
			rs=st.executeQuery();
			while (rs.next()) {
				user.setId(rs.getInt(1));
				user.setName(rs.getString(2));
				break;
			}
			
		}finally{
			if (null!=rs) {
				rs.close();
			}
			
			if (null!=st) {
				st.close();
			}
		}
		
		return user;
		

	}
	
	public List<User> queryAll(Connection con) throws SQLException,IOException {
		List<User> list=new ArrayList<>();
		String sql="select * from user";
		try {
			st=con.prepareStatement(sql);
			rs=st.executeQuery();
			while (rs.next()) {
				User user=new User();
				user.setId(rs.getInt(1));
				user.setName(rs.getString(2));
				list.add(user);
			}
			
		}finally{
			if (null!=rs) {
				rs.close();
			}
			
			if (null!=st) {
				st.close();
			}
		}
		
		return list;
		

	}
	
}

2、JDBC连接的测试类

1)、TestJdbc.java:数据库测试类

package cn.java.jdbc;

import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;


public class TestJdbc {
	
	public static void main(String[] args) {
		Connection con=null;
		try {		
			con=(Connection) ConnectionFactory.getInstance().getConnection();
			UserDao userDao=new UserDao();
			//con=(Connection) ConnectionFactory2.getInstance().getConnection();
			if (null!=con) {
				System.out.println("Link JDBC SUCESS");
				//userDao.insert(con, "zhangsir");
				//userDao.delete(con, 4);
				//userDao.update(con, 1, "david");
				List<User> list=userDao.queryAll(con);
				for (User user : list) {
					System.out.println("id="+user.getId()+" name="+user.getName());
				}
			}
			
		} catch (SQLException e) {
			e.printStackTrace();
	    } catch (IOException e) {
		e.printStackTrace();
	    }finally{
			if (null!=con) {
				try {
					con.close();
				} catch (SQLException e) {
				}
			}
		}
		
	}

}

三、JDBC连接总结

JDBC操作的基本步骤是:

1、创建Connection对象,传入SQL查询命令字符串;

2、获取PreparedStatement对象:通过Connection对象传入SQL查询命令获取;

3、获取ResultSet:对PreparedStatement执行executeUpdate()或者executeQurey()获取;

4、依次关闭打开的对象:先后关闭ResultSet、PreparedStatement和Connection对象.

猜你喜欢

转载自blog.csdn.net/j086924/article/details/51546876