首页 > 代码库 > 【Java】JDBC数据库连接

【Java】JDBC数据库连接

【是什么】

      JDBC全称JAVADataBaseConnectivity,即Java数据库连接,它是一种可执行SQL语句的Java API。程序员可以通过JDBCAPI连接到关系数据库,并使用结构化查询语句(即SQL)完成对数据库的查询、更新。

【作用】

       简单地说,JDBC可做三件事:与数据库建立连接、发送 操作数据库的语句并处理结果。下列代码段给出了以上三步的基本示例(太经典了就直接从百科中截取啦):

1.数据库建立连接:

Connection con = DriverManager.getConnection("jdbc:odbc:wombat","login","password");

2.发送操作数据库的语句:

Statement stmt = con.createStatement();
ResultSet rs =stmt.executeQuery("SELECT a, b, c FROM Table1");

3.对返回结果处理:

while (rs.next()) {
     int x = rs.getInt("a");
     String s = rs.getString("b");
     float f = rs.getFloat("c");
}

 【 JDBC连接数据实例】

   需要引入相应的驱动jar包,mysql-connector-java-5.1.26-bin.jar,网上下载即可。

sys-config.xml配置文件代码:   

<?xml version="1.0" encoding="UTF-8"?>
<config>
	<db-info>
		<driver-name>com.mysql.jdbc.Driver</driver-name>
		<url>jdbc:mysql://localhost:3306/drp?characterEncoding=UTF-8</url>
		<user-name>root</user-name>
		<password>123456</password>
	</db-info>
</config>

XMLConfigReader.java类用来解析配置文件:

package com.bjpowernode.drp.util;

import java.io.InputStream;

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

/**
 * 采用单例模式解析sys-config.xml文件
 * 
 * @author happy
 * 
 */
public class XmlConfigReader {

	// 懒汉式(延迟加载lazy)
	private static XmlConfigReader instance = null;

	// 保存jdbc相关配置信息
	private JdbcConfig jdbcConfig = new JdbcConfig();

	private XmlConfigReader() {
		SAXReader reader = new SAXReader();
		InputStream in = Thread.currentThread().getContextClassLoader()
				.getResourceAsStream("sys-config.xml");
		try {
			Document doc = reader.read(in);

			// 取得jdbc相关配置信息
			Element driverNameElt = (Element) doc
					.selectObject("/config/db-info/driver-name");
			Element urlElt = (Element) doc.selectObject("/config/db-info/url");
			Element userNameElt = (Element) doc
					.selectObject("/config/db-info/user-name");
			Element passwordElt = (Element) doc
					.selectObject("/config/db-info/password");

			// 设置jdbc相关的配置
			jdbcConfig.setDriverName(driverNameElt.getStringValue());
			jdbcConfig.setUrl(urlElt.getStringValue());
			jdbcConfig.setUserName(userNameElt.getStringValue());
			jdbcConfig.setPassword(passwordElt.getStringValue());

			System.out.println("读取jdbcConfig-->>" + jdbcConfig);

		} catch (DocumentException e) {
			e.printStackTrace();
		}
	}

	public static synchronized XmlConfigReader getInstance() {
		if (instance == null) {
			instance = new XmlConfigReader();
		}
		return instance;
	}

	/**
	 * 返回jdbc相关配置
	 * 
	 * @return
	 */
	public JdbcConfig getJdbcConfig() {
		return jdbcConfig;
	}
}

其他的解析方式见博客:http://blog.csdn.net/u013036274/article/details/52506721

ConnectionManager.java类用来封装一些connection方法:

package com.bjpowernode.drp.util;

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

/**
 * 采用ThreadLocal封装Connection
 * 
 * @author Administrator
 * 
 */
public class ConnectionManager {

	private static ThreadLocal<Connection> connectionHolder = new ThreadLocal<Connection>();

	/**
	 * 得到Connection
	 * 
	 * @return
	 */
	public static Connection getConnection() {
		// 先从线程变量中获取connection
		Connection conn = connectionHolder.get();
		// 如果在当前线程中没有绑定相应的Connection
		if (conn == null) {
			try {
				JdbcConfig jdbcConfig = XmlConfigReader.getInstance()
						.getJdbcConfig();
				Class.forName(jdbcConfig.getDriverName());
				conn = DriverManager.getConnection(jdbcConfig.getUrl(),
						jdbcConfig.getUserName(), jdbcConfig.getPassword());
				// 将Connection设置到ThreadLocal
				connectionHolder.set(conn);
			} catch (ClassNotFoundException e) {
				e.printStackTrace();
				throw new ApplicationException("系统错误,请联系系统管理员");
			} catch (SQLException e) {
				e.printStackTrace();
				throw new ApplicationException("系统错误,请联系系统管理员");
			}
		}
		return conn;
	}

	/**
	 * 关掉connection
	 */
	public static void closeConnection() {
		Connection conn = connectionHolder.get();
		if (conn != null) {
			try {
				conn.close();
				// 从ThreadLocal中清除Connection
				connectionHolder.remove();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
	}

	public static void close(Connection conn) {
		if (conn != null) {
			try {
				conn.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
	}

	public static void close(Statement pstmt) {
		if (pstmt != null) {
			try {
				pstmt.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
	}

	public static void close(ResultSet rs) {
		if (rs != null) {
			try {
				rs.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
	}

	public static void beginTransaction(Connection conn) {
		try {
			if (conn != null) {
				if (conn.getAutoCommit()) {
					conn.setAutoCommit(false); // 手动提交
				}
			}
		} catch (SQLException e) {
		}
	}

	public static void commitTransaction(Connection conn) {
		try {
			if (conn != null) {
				if (!conn.getAutoCommit()) {
					conn.commit();
				}
			}
		} catch (SQLException e) {
		}
	}

	public static void rollbackTransaction(Connection conn) {
		try {
			if (conn != null) {
				if (!conn.getAutoCommit()) {
					conn.rollback();
				}
			}
		} catch (SQLException e) {
		}
	}

}

补充:

oracle的连接:

    driverClass:oracle.jdbc.driver.OracleDriver
     url:jdbc:oracle:thin:@localhost:1521:orcl

【小结】

      但是每次都这样配置连接,是不是会很麻烦?如果是多个项目呢?当相似的事务多的时候,就要进行抽象,将公共的地方抽象成一个更高层的接口类。所以下面博客要介绍连接池啦。

【Java】JDBC数据库连接