滚滚向前滚

导航

 

目录

一、JDBC概念

JDBC全称是Java Database Connectivity,其中定义了一套标准的接口,不同的数据库厂商根据各自数据库的特点去实现这些接口。

二、使用JDBC步骤

  1. 装载驱动程序Driver,安装驱动管理Driver Manager,建立连接
  2. 创建语句对象
  3. 执行SQL语句
  4. 处理结果集
  5. 关闭资源(关闭陈述对象,关闭连接)

2.1 加载驱动

2.1.1 基本语法

Class.forName("驱动名称");

2.1.2 常见驱动(需要提前导入jar包)

  1. mysql

    com.mysql.jdbc.Driver

  2. oracle

    oracle.jdbc.driver.OracleDriver

2.2 建立连接

2.2.1 基本语法

Connection cnn = DriverManager.getconnection(url, 登录数据库用户名, 登录数据库密码);

2.2.2 常见url写法

  1. mysql
/*
 * jdbc:mysql://数据库ip地址:端口/数据库名称
 */
String url = "jdbc:mysql://192.168.0.188:3306/testBatch";

pom.xml文件配置:

<dependency> 
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>5.1.24</version>
</dependency>
  1. oracle
/*
 * jdbc:oracle:thin:@数据库ip地址:端口:数据库名称
 */
String url = "jdbc:oracle:thin:@192.168.0.188:3306:testBatch";

pom.xml文件配置:

<dependency>    
    <groupId>com.oracle</groupId>    
    <artifactId>ojdbc14</artifactId>    
    <version>10.2.0.4.0</version>
</dependency>
<!-- 有问题,搜索不到这个包 -->

2.3 创建语句对象

Statement stmt = conn.createStatement();

2.4 执行sql语句

2.4.1 执行DQL语句

/*
 * executeQuery返回ResultSet结果集,代表二位查询结果,一般使用for循环遍历处理,查询失败抛出异常
 */
ResultSet rs =  stmt.executeQuery(sql);

2.4.2 执行DML语句

/*
 * executeUpdate返回结果是一个int类型,这条sql语句表示更新/添加/删除的记录数,失败抛出异常
 */
int flag =  stmt.executeUpdate(sql);

2.4.3 执行DDL语句

boolean flag =  stmt.execute(sql);
// 这个语句可以执行任何语句,但是一般执行DDL语句

/*
 * 返回true代表有结果集,返回false代表没有结果集
 * 创建失败跑出异常
 */

2.4.4 提交事务

conn.commit();

2.5 清理资源

// 关闭处理结果集
rs.close();

// 关闭陈述对象
stmt.close();

/*
 * 上面两个操作应该在sql语句执行处理完就关闭,减少内存资源的开销
 */
 
// 关闭连接
conn.close();

三、ResultSet解析

/*
 * 解析ResultSet结果集
 */
while(rs.next()){
	int id = rs.getInt(1);
	String sPassword = rs.getString(2);
	String sName = rs.getString(3);	
	System.out.println("id = " + id + ", " + "sName = " + sName + ", "  + "sPassword =" + sPassword);
}

四、案例

package com.mysql.demo;

import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.concurrent.locks.StampedLock;
import java.sql.Connection;

public class MysqlConn {
	public static void main(String[] args) {
		Connection conn = null;
		Statement stmt = null;
		try {
			// 装载驱动
			Class.forName("com.mysql.jdbc.Driver");
			
			String url = "jdbc:mysql://127.0.0.1:3306/mysql";
			String user = "gupan";
			String pwd = "free930923";
			// 建立连接
			conn = DriverManager.getConnection(url, user, pwd);
			
			// 输出conn引用对象的实际类型
//			System.out.println(conn.getClass());
			stmt = conn.createStatement();
			
			// 执行sql
			/*
			 * 返回true代表有结果集,返回false代表没有结果集
			 * 创建失败跑出异常
			 */
			String ddl1 = "CREATE TABLE gupan_demo01 ("
					+ "id int primary key auto_increment, " 
					+ "password varchar(30), "
					+ "name varchar(30)" 
					+ ");";
//			boolean flag = stmt.execute(ddl1);
//			System.out.println(flag);
			
			String dml1 = "INSERT INTO " 
					+ "gupan_demo01 "
					+ "( "
					+ "name, password "
					+ ") " 
					+ "VALUES " 
					+ "( "
					+ "'gupan', '123456'"
					+ "), "
					+ "( "
					+ "'yuangungun', '234567'"
					+ ")"
					;
			/*
			 * executeUpdate返回结果是一个int类型,这条sql语句表示更新/添加/删除的记录数,失败抛出异常
			 */
//			int rows = stmt.executeUpdate(dml1);
//			System.out.println(rows);
			
			/*
			 * executeQuery返回ResultSet结果集,代表二位查询结果,一般使用for循环遍历处理,查询失败抛出异常
			 */
			String dql1 = "select * from gupan_demo01;";
			ResultSet rs = stmt.executeQuery(dql1);
			
			/*
			 * 解析ResultSet结果集
			 */
			while(rs.next()){
				int id = rs.getInt(1);
				String sPassword = rs.getString(2);
				String sName = rs.getString(3);	
				System.out.println("id = " + id + ", " + "sName = " + sName + ", "  + "sPassword =" + sPassword);
			}
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally {
			try {
				// 关闭陈述对象
				stmt.close();
				// 关闭数据库连接
				conn.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
}

五、封装

封装数据库连接:

package com.db.utils;

import java.io.Closeable;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

import javax.management.RuntimeErrorException;
/**
 * 封装数据库连接过程,简化数据库连接
 * 
 * @author gupan
 *
 */
public class DbUtils {
	static String driver;
	static String url;
	static String user;
	static String pwd;
	
	/**
	 * 初始化静态属性
	 */
	static {
		Properties cfg = new Properties();
		InputStream in = DbUtils.class.getClassLoader().getResourceAsStream("db.properties");
		try {
			cfg.load(in);
//			System.out.println(cfg);
			// 初始化连接参数
			driver = cfg.getProperty("jdbc.driver");
			url = cfg.getProperty("jdbc.url");
			user = cfg.getProperty("jdbc.user");
			pwd = cfg.getProperty("jdbc.pwd");
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			throw new RuntimeException(e);
		}finally {
			try {
				if (in != null) {
					in.close();
				}
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				throw new RuntimeException(e);
			}
		}
	}
	
	public static Connection getConnection(){
		Connection conn = null;
		// 装载驱动
		
		try {
			Class.forName(driver);
			// 建立连接
			conn = DriverManager.getConnection(url, user, pwd);
			
			return conn;
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			throw new RuntimeException(e);
		} catch (SQLException e) {
			e.printStackTrace();
			throw new RuntimeException(e);
		}
	}
	/**
	 * 封锁复杂的数据库关闭方法
	 * @param conn
	 */
	public static void close(Connection conn) {		
		if (conn != null) {
			try {
				conn.close();
			} catch (SQLException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
		}
	}
}

执行数据库操作:

package com.db.utils;

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

import java.sql.Statement;

public class UseUtil2Conn {
	public static void main(String[] args) {
		Connection conn = null;
		Statement stmt = null;
		try {
			conn = DbUtils.getConnection();	
			stmt = conn.createStatement();
			
			String ddl1 = "CREATE TABLE gupan_demo01 ("
					+ "id int primary key auto_increment, " 
					+ "password varchar(30), "
					+ "name varchar(30)" 
					+ ");";
//			boolean flag = stmt.execute(ddl1);
//			System.out.println(flag);
			
			String dml1 = "INSERT INTO " 
					+ "gupan_demo01 "
					+ "( "
					+ "name, password "
					+ ") " 
					+ "VALUES " 
					+ "( "
					+ "'gupan', '123456'"
					+ "), "
					+ "( "
					+ "'yuangungun', '234567'"
					+ ")"
					;
//			int rows = stmt.executeUpdate(dml1);
//			System.out.println(rows);
			
			String dql1 = "select * from gupan_demo01;";
			ResultSet rs = stmt.executeQuery(dql1);
			
			while(rs.next()){
				int id = rs.getInt(1);
				String sPassword = rs.getString(2);
				String sName = rs.getString(3);	
				System.out.println("id = " + id + ", " + "sName = " + sName + ", "  + "sPassword =" + sPassword);
			}
			
			/*
			 * 对于多条查询语句,应该释放查询结果,释放语句对象 ,否则会扩大内存开销,影响程序性能
			 */
			rs.close();// 释放查询结果
			stmt.close(); // 释放语句对象
		}catch (Exception e){
			e.printStackTrace();
			DbUtils.close(conn);
		}
	}
}
posted on 2018-06-04 21:16  滚滚向前滚  阅读(217)  评论(0编辑  收藏  举报