Day28-JDBC基础

总结

我是最棒的!基础不牢,地动山摇!

JDBC基础

JDK6有一个新特性,不需要手动加载驱动,但是我们在JavaEE开发中还是要手动去加载驱动

Class.forName("foo.bah.Driver");

操作步骤

  1. 导入jar包:驱动包

  • 加:加载驱动

  • 连:获取数据库连接对象

  • 语:获取数据库会话语句

  • 执:执行SQL语句

  • 释:释放资源

常用类和方法

//需要注意包不要导入错误
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;

//加载驱动
Class.forName("foo.bah.Driver");
//创建连接对象
Connection conn = DriverManager.getConnection();
//创建数据库会话对象
Statement st = conn.createStatement;
//DDL,DML语句使用executeUpdate() 创建数据库,增删改表等
st.executeUpdate();
//DQL使用executeQuery() 静态select操作返回结果集
ResultSet rs = st.executeQuery();
//rs类似迭代器,有next()方法,还有两种get方法
//getXxx(int index) 获取Xxx类型的属性,index为列索引,从1开始
//getXxx(String name) 获取Xxx类型的属性,name为列名
while(rs.next()){
    //获取id
    rs.getLong(1);
    //获取name
    rs.getString("name");
}

抽取工具类JDBCUtil

通过配置文件解决硬编码问题

driverName=com.mysql.jdbc.Driver
url=jdbc:mysql:///webjdbc
username=root
password=root

工具类

package cn.itsource.jdbctest;

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 JDBCUtil {
	/**初始化四大重要属性*/
	private static String driverName;
	private static String url;
	private static String user;
	private static String password;
	
	/**
	 * 通过静态代码块,只需要加载一次驱动
	 */
	static{
		
		try {
			Properties p = new Properties();
			p.load(Thread.currentThread().getContextClassLoader().getResourceAsStream("db.properties"));
			driverName = p.getProperty("driverName");
			url = p.getProperty("url");
			user = p.getProperty("username");
			password = p.getProperty("password");
			Class.forName(driverName);
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	/**
	 * 获取连接对象
	 * @return
	 */
	public static Connection getConnection(){
		
		Connection connection = null;
		
		try {
			connection = DriverManager.getConnection(url,user,password);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		
		return connection;
	}
	
	/**
	 * 释放资源
	 * @param conn
	 * @param st
	 * @param rs
	 */
	public static void close(Connection conn,Statement st,ResultSet rs){
		try {
			if(conn != null){
				conn.close();
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}finally {
				try {
					if(st != null){
						st.close();
					}
				} catch (SQLException e) {
					e.printStackTrace();
				}finally {
					try {
						if(rs != null){
							rs.close();
						}			
					} catch (SQLException e) {
						e.printStackTrace();
					}
				}
			
		}
	}
}

实例

原生的jdbc实现增删改查操作

package cn.itsource.jdbctest;

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

public class JDBCTest {

	public static void main(String[] args) throws Exception {
//		insert();
//		update();
//		delete();
//		createTable2();
//		deleteTable();
//		insert2();
//		update2();
		delete2();
				
	}
	
	public static void createTable() throws Exception{
		//加
		Class.forName("com.mysql.jdbc.Driver");
		//连
		String url = "jdbc:mysql://localhost:3306/webjdbc";
		String user = "root";
		String password = "root";
		
		Connection connection = DriverManager.getConnection(url,user,password);
		//语
		Statement st = connection.createStatement();
		String sql = "create table test1("
				+ "id bigint primary key auto_increment,"
				+ "name varchar(20) not null,"
				+ "age int)";
		int i = st.executeUpdate(sql);
		System.out.println(i);
		
		st.close();
		connection.close();
	}
	
	public static void insert() throws Exception{
		//加
		Class.forName("com.mysql.jdbc.Driver");
		//连
		String url = "jdbc:mysql://localhost:3306/webjdbc";
		String user = "root";
		String password = "root";
		
		Connection connection = DriverManager.getConnection(url,user,password);
		//语
		Statement st = connection.createStatement();
		String sql = "insert into test1 values (null,'xxx',20)";
		
		//执行
		int i = st.executeUpdate(sql);
		System.out.println(i);
		
		//释放
		st.close();
		connection.close();
	}
	
	public static void update(){
		Connection conn = null;
		Statement st = null;
		
		try {
			//加
			Class.forName("com.mysql.jdbc.Driver");
			//连
			
			String url = "jdbc:mysql://localhost:3306/webjdbc";
			String username = "root";
			String password = "root";
			
			conn = DriverManager.getConnection(url,username,password);
			//语
			st = conn.createStatement();
			//执行
			String sql = "update test1 set name = 'ddd' where id = 1";
			int i = st.executeUpdate(sql);
			System.out.println(i);
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (SQLException e) {
			e.printStackTrace();
		}finally {
			try {
				if(st!= null){
					st.close();
				}
			} catch (SQLException e) {
				e.printStackTrace();
			}finally {
				try {
					if(conn != null){
						conn.close();
					}
				} catch (SQLException e) {
					e.printStackTrace();
				}
			}
		}
	}
	
	public static void delete(){
		Connection conn = null;
		Statement st = null;
		
		try {
			//加
			Class.forName("com.mysql.jdbc.Driver");
			//连
			
			String url = "jdbc:mysql://localhost:3306/webjdbc";
			String username = "root";
			String password = "root";
			
			conn = DriverManager.getConnection(url,username,password);
			//语
			st = conn.createStatement();
			//执行
			String sql = "delete from test1 where id = 1";
			int i = st.executeUpdate(sql);
			System.out.println(i);
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (SQLException e) {
			e.printStackTrace();
		}finally {
			try {
				if(st!= null){
					st.close();
				}
			} catch (SQLException e) {
				e.printStackTrace();
			}finally {
				try {
					if(conn != null){
						conn.close();
					}
				} catch (SQLException e) {
					e.printStackTrace();
				}
			}
		}
	}
	
	public static void createTable2(){
		Connection connection = JDBCUtils.getConnection();
		Statement st = null;
		
		String sql = "create table test2("
				+ "id bigint primary key auto_increment,"
				+ "name varchar(20) not null,"
				+ "age int)";
		
		try {
			st = connection.createStatement();
			st.executeUpdate(sql);
		} catch (SQLException e) {
			e.printStackTrace();
		}finally {
			JDBCUtils.close(st, connection);
		}
		
	}
	
	public static void deleteTable(){
		Connection connection = JDBCUtils.getConnection();
		Statement st = null;
		
		String sql = "drop table test2";
		
		try {
			st = connection.createStatement();
			st.executeUpdate(sql);
		} catch (SQLException e) {
			e.printStackTrace();
		}finally {
			JDBCUtils.close(st, connection);
		}
		
	}
	
	public static void insert2(){
		Connection connection = JDBCUtils.getConnection();
		Statement st = null;
		
		String sql = "insert into test1 values (null,'yyy',18)";
		try {
			st = connection.createStatement();
			st.executeUpdate(sql);
		} catch (SQLException e) {
			e.printStackTrace();
		}finally {
			JDBCUtils.close(st, connection);
		}
		
	}
	
	public static void update2(){
		Connection connection = JDBCUtils.getConnection();
		Statement st = null;
		
		String sql = "update test1 set name = 'ddd' where id = 2";
		
		try {
			st = connection.createStatement();
			st.executeUpdate(sql);
		} catch (SQLException e) {
			e.printStackTrace();
		}finally {
			JDBCUtils.close(st, connection);
		}
	}
	
	public static void delete2(){
		Connection connection = JDBCUtils.getConnection();
		Statement st = null;
		
		String sql = "delete from test1 where id = 2";
		
		try {
			st = connection.createStatement();
			st.executeUpdate(sql);
		} catch (SQLException e) {
			e.printStackTrace();
		}finally {
			JDBCUtils.close(st, connection);
		}
		
	}

}

DAO接口,实现类与domain

面向接口编程,有更高的可扩展性

DAO接口

package cn.itsource.dao;

import java.util.List;

import cn.itsource.domain.Student;

public interface StudnetDAO {
	/**
	 * 添加一个学生
	 * @param stu
	 */
	void add(Student stu);
	
	/**
	 * 删除一个学生
	 * @param id
	 */
	void remove(Long id);
	
	/**
	 * 修改一个学生的属性
	 * @param stu
	 */
	void update(Student stu);
	
	/**
	 * 查询指定学生的信息
	 * @param id
	 */
	Student get(Long id);
	
	/**
	 * 查询所有学生的信息
	 */
	List<Student> getAll();
}

实现类

package cn.itsource.dao.impl;

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

import cn.itsource.dao.StudnetDAO;
import cn.itsource.domain.Student;
import cn.itsource.jdbctest.JDBCUtil;

public class StudentDAOImpl implements StudnetDAO {

	@Override
	public void add(Student stu) {
		
		Connection connection = JDBCUtil.getConnection();
		Statement st = null;
		
		String sql = "insert into test1 values (null,'";
		StringBuilder sb = new StringBuilder(sql);
		sb.append(stu.getName()).append("',").append(stu.getAge()).append(")");
		System.out.println(sb);
		try {
			st = connection.createStatement();
			st.executeUpdate(sb.toString());
		} catch (SQLException e) {
			e.printStackTrace();
		}finally {
			JDBCUtil.close(connection, st, null);
		}
	}

	@Override
	public void remove(Long id) {
		Connection conn = null;
		Statement st = null;
		
		try {
			conn = JDBCUtil.getConnection();
			st = conn.createStatement();
			String sql = "delete from test1 where id = ";
			StringBuilder sb = new StringBuilder(sql);
			sb.append(id);
			System.out.println(sb);
			st.executeUpdate(sb.toString());
		} catch (SQLException e) {
			e.printStackTrace();
		}finally {
			JDBCUtil.close(conn, st, null);
		}
	}

	@Override
	public void update(Student stu) {
		Connection conn = null;
		Statement st = null;
		
		try {
			conn = JDBCUtil.getConnection();
			st = conn.createStatement();
			
			String sql = "update test1 set name = '";
			StringBuilder sb = new StringBuilder(sql);
			sb.append(stu.getName()).append("',").append("age = ").append(stu.getAge())
			.append(" where id = ").append(stu.getId());
			System.out.println(sb);
			
			st.executeUpdate(sb.toString());
		} catch (SQLException e) {
			e.printStackTrace();
		}finally {
			JDBCUtil.close(conn, st, null);
		}
	}

	@Override
	public Student get(Long id) {
		Student stu = null;
		Connection conn = null;
		Statement st = null;
		ResultSet rs = null;
		
		try {
			conn = JDBCUtil.getConnection();
			st = conn.createStatement();
		
			String sql = "select * from test1 where id = ";
			StringBuilder sb = new StringBuilder(sql);
			sb.append(id);
			
			rs = st.executeQuery(sb.toString());
			if(rs.next()) {
				stu = new Student();
				stu.setId(rs.getLong(1));
				stu.setName(rs.getString(2));
				stu.setAge(rs.getInt(3));
//				System.out.println(rs.getLong(1));
//				System.out.println(rs.getString(2));
//				System.out.println(rs.getInt(3));
			}
			
		} catch (SQLException e) {
			e.printStackTrace();
		}finally {
			JDBCUtil.close(conn, st, rs);
		}
		return stu;
	}

	@Override
	public List<Student> getAll() {
		List<Student> list = new ArrayList<Student>();
		Connection conn = null;
		Statement st= null;
		ResultSet rs = null;
		
		try {
			conn = JDBCUtil.getConnection();
			st = conn.createStatement();
			String sql = "select * from test1";
			
			rs = st.executeQuery(sql);
			while(rs.next()){
				Student student = new Student();
				student.setId(rs.getLong(1));
				student.setName(rs.getString(2));
				student.setAge(rs.getInt(3));
				list.add(student);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return list;
	}

}

domain

package cn.itsource.domain;

public class Student {
	private Long id;
	private String name;
	private Integer age;
	
	public Long getId() {
		return id;
	}
	public void setId(Long id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public Integer getAge() {
		return age;
	}
	public void setAge(Integer age) {
		this.age = age;
	}
	
	@Override
	public String toString() {
		return "[" + id + ", " + name + ", " + age + "]";
	}	
}

猜你喜欢

转载自blog.csdn.net/t384061961/article/details/100675493