JDBC连接Oracle数据库,实现增删改查,简单封装jdbc

JDBC

  • JDBC是一套标准(接口),用来连接【关系型数据库】。各个数据库厂商去实现具体的功能,用户使用时使用相同一套标准即可。但是在使用时得导入不同公司提供的包(里面包含了具体实现)。
  • 连接数据库的方式,常见有两种: ODBC和JDBC,分属两个不同的阵营。其中JDBC是java版本的ODBC.
  • ODBC(Open Database Connectivity)开放的数据库连接,由微软开发出来。是一套公共的接口(标准),用来连接数据库。

连接数据库5(6)大步骤

在阐明步骤之前要先说JDBC的4要素
1).String driver = “jar包Driver类全包名”;
告诉我们具体数据库驱动在哪里,方便后期注册。
String dirver = “oracle.jdbc.driver.OracleDriver”;

2).URL 确定连接到那个具体的数据库
jdbc:oracle:oci:@< SID > oci连接方式
jdbc:oracle:thin:@< SID > thin连接方式
String url = “jdbc:oracle:thin:@127.0.0.1:1521:XE”;

3).String user = “用户名”;

4).String password = “密码”;

  1. 注册驱动(3种方法)
    a.使用类加载器
    String driverName = “oracle.jdbc.driver.OracleDriver”;
    Class.forName(driverName);
    b.实例化一个驱动对象
    实例化驱动对象
    Driver driver = new oracle.jdbc.driver.OracleDriver();
    注册驱动
    DriverManager.registerDriver(driver);
    c.使用property
    System.setProperty(“jdbc.drivers”, “oracle.jdbc.driver.OracleDriver”);
    使用【系统配置】进行驱动注册,其中【第一个参数值固定】,第二个参数为驱动类的全包名。
Class.forName(oracle.jdbc.driver.OracleDriver);
  1. 建立连接(2种方式)
    第一种是利用DriverManager.getConnection(url, user, passwd);
    第二种是利用Driver类直接连接(其实第一种底层也是通过Driver建立的连接)。
    Driver driver = new oracle.jdbc.driver.OracDriver();
    Properties info = new Properties();
    info.setProperty(“user”,"");
    info.setProperty(“password”,"");
    conn = driver.connect(url,info);

    关于DriverManager和Driver的关系
    一个DriverManager可以管理多个Driver,在具体进行数据库连接时,管理类借助Driver里面的connect方法建立连接。

conn = DriverManager.getConnection(jdbc:oracle:thin:@127.0.01:1521:XE, oracle, oracle);
  1. 创建Statement对象或PrepareStatement对象
stmt = conn.createStatement();

注意:要执行的sql语句可以分为同构异构
异构 结构不同的语句。Statement语句执行,每次执行sql语句,都会把sql语句通过网络发送到服务器,然后让服务器实现功能。

Statement stmt = conn.createStatement();
	String sql = "select * from s_emp";
    stmt.execute(sql);
    stmt.executeQuery(sql);
    stmt.executeUpdate(sql);

一共有三种执行方式,他们都可以正常执行select insert update delete语句,区别在于返回值类型。
execute(sql)返回boolean,执行【返回结果集则true】,否则false;
executeUpdate(sql)【返回int】,执行影响了多少条数据;
executeQuery(sql)返回结果集ResultSet。

同构 结构相同的sql语句。PrepareStatement预编译同构sql语句,在实际使用时,可以提前将Sql语句发送给数据库进行【预编译】,然后每次只需要传输值即可,这样子可以提高效率。如:

String sql = "insert into student(id,name,age,birthday) values(?,?,?,?)";
	PrepareStatement ps = conn.prepareStatement(sql);
	ps.setInt(1,7);
	ps.setString(2, "王五");
	ps.setInt(3, 21);
  1. 执行sql语句
String sql = "select * from student";
  1. 如果是sql语句是Select语句的话,操作查询返回的结果集
    这一步骤针对sql语句是select语句时,才会有查询结果返回。将查询回来的学生信息封装成一个学生对象,放入list集合中。
List list = new ArrayList<>();
			Student s = null;
			while(rs.next()){
				long id = rs.getLong("id");
				String name = rs.getString("name");
				int age = rs.getInt("age");
				s = new Student(id, name, age);
				list.add(s);
			}
  1. 关闭连接通道
if(stmt!=null)
	stmt.close();
if(conn!=null)
	conn.close();

Statement增删改查

package com.briup.jdbcday1;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

import org.junit.Test;

public class StatementTest {
	private static String driver = "oracle.jdbc.driver.OracleDriver";
	private static String url = "jdbc:oracle:thin:@127.0.01:1521:XE";
	private static String user = "oracle";
	private static String password = "oracle";
	@Test
	public void test_insert(){
		Connection conn = null;
		Statement stmt = null;
		try {
			//1.注册驱动
			Class.forName(driver);
			//2.建立连接
			conn = DriverManager.getConnection(url, user, password);
			System.out.println(conn);
			//3.创建Statement
			stmt = conn.createStatement();
			//4.执行sql
			Student s = new Student(4, "tom4", 18);
			String sql = "insert into student values("+s.getId()+",'"+s.getName()+"',"+s.getAge()+")";
//			stmt.execute(sql);//boolean 
//			stmt.executeQuery(sql);//ResultSet//select
//			stmt.executeUpdate(sql);//int
			stmt.execute(sql);
			//5.操作结果集(如果有)
			
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
			//6.关闭资源
			try {
				if(stmt!=null)stmt.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			try {
				if(conn!=null)conn.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	
	}

	@Test
	public void test_update(){
		Connection conn = null;
		Statement stmt = null;
		try {
			Class.forName(driver);
			conn = DriverManager.getConnection(url, user, password);
			System.out.println(conn);
			stmt = conn.createStatement();
			String sql = "update student set name='zs' where id= 1";
			stmt.execute(sql);
			
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
			try {
				if(stmt!=null)stmt.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			try {
				if(conn!=null)conn.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		
	}
	@Test
	public void test_delete(){
		Connection conn = null;
		Statement stmt = null;
		try {
			Class.forName(driver);
			conn = DriverManager.getConnection(url, user, password);
			System.out.println(conn);
			stmt = conn.createStatement();
			String sql = "delete from student where id = 1";
			stmt.execute(sql);
			
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
			try {
				if(stmt!=null)stmt.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			try {
				if(conn!=null)conn.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		
	}
	@Test
	public void test_select(){
		Connection conn = null;
		Statement stmt = null;
		try {
			Class.forName(driver);
			conn = DriverManager.getConnection(url, user, password);
			System.out.println(conn);
			stmt = conn.createStatement();
			String sql = "select * from student";
			ResultSet rs = stmt.executeQuery(sql);
			//5.操作结果集
			List list = new ArrayList<>();
			Student s = null;
			while(rs.next()){
				long id = rs.getLong("id");
				String name = rs.getString("name");
				int age = rs.getInt("age");
				s = new Student(id, name, age);
				list.add(s);
			}
			for(Student stu : list){
				System.out.println(stu);
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
			try {
				if(stmt!=null)stmt.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			try {
				if(conn!=null)conn.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		
	}
}

PreparedStatement新增的两种方式

package com.briup.jdbcday1;

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

import org.junit.Test;


public class PreparedStatementTest {
	private static String driver = "oracle.jdbc.driver.OracleDriver";
	private static String url = "jdbc:oracle:thin:@127.0.01:1521:XE";
	private static String user = "oracle";
	private static String password = "oracle";
	@Test
	public void test_insert(){
		Connection conn = null;
		PreparedStatement ps = null;
		try {
			//1.注册驱动
			Class.forName(driver);
			//2.建立连接
			conn = DriverManager.getConnection(url, user, password);
			//3.创建Statement
			String sql = "insert into student values(?,?,?)";
			ps = conn.prepareStatement(sql);
			//4.执行sql
			ps.setLong(1, 5L);
			ps.setString(2, "tom5");
			ps.setInt(3, 18);
			ps.execute();//不能写成ps.execute(sql);
			//5.操作结果集(如果有)
			
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
			//6.关闭资源
			try {
				if(ps!=null)ps.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			try {
				if(conn!=null)conn.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	
	}
	
	//批量新 增
	@Test
	 void test_insert2(){
		Connection conn = null;
		PreparedStatement ps = null;
		try {
			//1.注册驱动
			Class.forName(driver);
			//2.建立连接
			conn = DriverManager.getConnection(url, user, password);
			//设置手动提交事务
			conn.setAutoCommit(false);
			//3.创建Statement
			String sql = "insert into student values(?,?,?)";
			ps = conn.prepareStatement(sql);
			//4.执行sql
			for(int i=1;i<11;i++){
				ps.setLong(1, i);
				ps.setString(2, "tom"+i);
				ps.setInt(3, 18);
				ps.execute();//不能写成ps.execute(sql);
			}
			//5.操作结果集(如果有)
			conn.commit();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
			//6.关闭资源
			try {
				if(ps!=null)ps.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			try {
				if(conn!=null)conn.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		
	}
}

构建连接工厂

上面的写法需要写大量的重复代码,所以最好将这些步骤封装起来,4要素也放在配置文件中直接读取后使用.
配置文件:文件名db.properties

driver=oracle.jdbc.driver.OracleDriver
url=jdbc:oracle:thin:@127.0.0.1:1521:XE
user=oracle
password=oracle

连接工厂

package com.briup.jdbcday2;

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

public class ConnectionFactory {
	private static String driver;
	private static String url;
	private static String user;
	private static String password;
	static{
		try {
			Properties p=new Properties();
			p.load(ConnectionFactory.class.getResourceAsStream("db.properties"));
			driver=p.getProperty("driver");
			url=p.getProperty("url");
			user=p.getProperty("user");
			password=p.getProperty("password");
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public static Connection getConnection() {
		Connection conn = null;
		try {
			// 1.注册驱动
			Class.forName(driver);
			// 2.建立连接
			conn = DriverManager.getConnection(url, user, password);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return conn;
	}

	public static void close(Connection conn, Statement stmt) {
		close(null, conn, stmt);
	}

	public static void close(ResultSet rs, Connection conn, Statement stmt) {
		try {
			if (rs != null)
				rs.close();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		try {
			if (stmt != null)
				stmt.close();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		try {
			if (conn != null)
				conn.close();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	public static void main(String[] args) {
		
	}
}

JDBC封装工具类

package com.briup.jdbcday2;

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

public class JDBCUtil {

	public static void execute_DML_stmt(String sql) {
		Connection conn = null;
		Statement stmt = null;
		try {
			conn = ConnectionFactory.getConnection();
			stmt = conn.createStatement();
			stmt.execute(sql);
			ConnectionFactory.close(conn, stmt);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}	
	}
	
	public static void execute_select_stmt(String sql,IWorkAdapter work) {
		Connection conn = null;
		Statement stmt = null;
		try {
			conn = ConnectionFactory.getConnection();
			stmt = conn.createStatement();
			ResultSet rs = stmt.executeQuery(sql);
			//处理结果集
			work.processRs(rs);
			ConnectionFactory.close(conn, stmt);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	public static void execute_DML_ps(String sql, IWorkAdapter work) {
		Connection conn = null;
		PreparedStatement ps = null;
		try {
			conn = ConnectionFactory.getConnection();
			ps=conn.prepareStatement(sql);
			work.setValues(ps);
			ps.execute();
			//ps.executeBatch();
			ConnectionFactory.close(conn, ps);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}	
	}
	
	public static void execute_select_ps(String sql, IWorkAdapter work) {
		Connection conn = null;
		PreparedStatement ps = null;
		ResultSet rs=null;
		try {
			conn = ConnectionFactory.getConnection();
			ps=conn.prepareStatement(sql);
			work.setValues(ps);
			rs = ps.executeQuery();
			work.processRs(rs);
			ConnectionFactory.close(conn, ps);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}	
	}
	
}

两个接口,一个用于处理结果集,一个用于设置参数

package com.briup.jdbcday2;

import java.sql.PreparedStatement;
import java.sql.ResultSet;

public interface IWork {

	public void processRs(ResultSet rs);

	public void setValues(PreparedStatement ps);

	
		
}

package com.briup.jdbcday2;

import java.sql.PreparedStatement;
import java.sql.ResultSet;

public abstract class IWorkAdapter implements IWork{

	@Override
	public void processRs(ResultSet rs) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void setValues(PreparedStatement ps) {
		// TODO Auto-generated method stub
		
	}
	
}

使用封装JDBC对数据库进行增删改查

package com.briup.jdbcday2;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class JDBCWork2 {
	public static void main(String[] args) {
		Teacher teacher =new Teacher(10,"椿",8000);
		List list=new ArrayList<>();
		for(int i=0;i<500;i++){
			list.add(new Teacher(i,"teacher"+i,25));
		}
		//teacherInsert(teacher);
		//teacherUpdate(teacher);
		//teacherDelete(teacher);
		teacherSelect(teacher);
		//teacherInsertBatch(list);
	}
	
	public static void teacherInsert(Teacher teacher){
		String sqlI="insert into teacher1 values(?,?,?)";
		
		JDBCUtil.execute_DML_ps(sqlI, new IWorkAdapter() {
			@Override
			public void setValues(PreparedStatement ps) {
				try {
					ps.setLong(1, teacher.getId());
					ps.setString(2, teacher.getName());
					ps.setInt(3, teacher.getAge());
				} catch (SQLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		});
	}
	
	public static void teacherUpdate(Teacher teacher){
		String sqlU="update teacher1 set name= ? where id = ?";
		JDBCUtil.execute_DML_ps(sqlU, new IWorkAdapter() {
			@Override
			public void setValues(PreparedStatement ps) {
				try {
					ps.setString(1, "湫");
					ps.setLong(2, teacher.getId());
				} catch (SQLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		});
	}
	
	public static void teacherDelete(Teacher teacher){
		String sqlD="delete from teacher1 where id =?";
		JDBCUtil.execute_DML_ps(sqlD, new IWorkAdapter() {
			@Override
			public void setValues(PreparedStatement ps) {
				try {
					ps.setLong(1, teacher.getId());
				} catch (SQLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		});
	}
	
	public static void teacherSelect(Teacher teacher){
		String sqlS="select * from teacher1 where id=?";
		JDBCUtil.execute_select_ps(sqlS, new IWorkAdapter() {
			Teacher t = null;
			@Override
			public void setValues(PreparedStatement ps) {
				try {
					ps.setLong(1, teacher.getId());
					
				} catch (SQLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			
			@Override
			public void processRs(ResultSet rs) {
				try {
					
					while (rs.next()) {
							
						long id = rs.getLong("id");
						String name = rs.getString("name");
						int age = rs.getInt("age");
						t = new Teacher(id, name, age);
						System.out.println(t);
					}
				} catch (SQLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		});
	}
	
	public static void teacherInsertBatch(List list){
		String sqlI="insert into teacher1 values(?,?,?)";
		
		JDBCUtil.execute_DML_ps(sqlI, new IWorkAdapter() {
			@Override
			public void setValues(PreparedStatement ps) {
				try {
					for(int i=0;i<500;i++){
						ps.setLong(1, list.get(i).getId());
						ps.setString(2, list.get(i).getName());
						ps.setInt(3, list.get(i).getAge());
						ps.addBatch();
					}
					
				} catch (SQLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		});
	}

}

你可能感兴趣的:(java复习)