您的位置:首页 > 数据库 > MySQL

MySQL的JDBC连接

2019-06-15 07:32 2266 查看

MySQL的JDBC连接

  • JDBC添加数据
  • 封装连接工具
  • 更新数据和事务
  • 删除数据
  • 查询数据
  • MySQL的JDBC概念

    JDBC 是 Java Database Connective的缩写,表示使用Java去连接数据库进行数据操作的过程

    MySQL的JDBC

    1. 创建动态项目-以eclipse为例,首先要创建动态项目
    2. 连接开发包(在www.mvnrepository.com下载)
    3. 在项目中导入驱动包
    • 可以使用build-path配置方式导入驱动包


    • 也可以直接将驱动包拷贝到项目的 lib 目录下

    JDBC添加数据

    使用Java连接数据库

    package com.berger.test;
    
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.Statement;
    
    public class TestMysql {
    //链接地址
    private static String URL = "jdbc:mysql://localhost:3306/demo?useSSL=true&useUnicode=true&characterEncoding=UTF-8";
    //驱动名称
    private static String DRIVER = "com.mysql.jdbc.Driver";
    //用户名
    private static String USER = "root";
    //密码
    private static String PASSWORD = "1234";
    
    //加载驱动信息
    static {
    try {
    Class.forName(DRIVER);
    } catch (ClassNotFoundException e) {
    e.printStackTrace();
    }
    }
    
    public static void main(String[] args) throws Exception {
    //获取Connection对象
    Connection conn = DriverManager.getConnection(URL, USER, PASSWORD);
    System.out.println(conn);
    
    //准备一条sql语句
    String sql = "INSERT INTO emp(empno,ename,job,sal,hiredate,mgr,comm,deptno) "
    + "VALUES(1002,'张三','总裁',9000,NOW(),null,2000,10)";
    //获取发送sql语句的对象
    //获取方法一,PreparedStatement可以对sql语句预编译,在数据库中直接执行,效率高
    //		PreparedStatement pst = conn.prepareStatement(sql);
    //		int row = pst.executeUpdate();
    //		System.out.println("插入了 " + row + " 行数据。");
    
    //获取方法二,Statement不会进行预编译,且容易出现错误
    Statement st = conn.createStatement();
    int row = st.executeUpdate(sql);
    System.out.println("插入了 " + row + " 行数据。");
    }
    }

    封装连接工具

    将连接代码放入一个工具类

    package com.berger.utils;
    
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.SQLException;
    
    public class ConnectionUtil {
    //数据库地址
    private static String URL="jdbc:mysql://localhost:3306/demo?useSSL=true&useUnicode=true&characterEncoding=UTF-8";
    //取得驱动程序
    private static String DRIVER="com.mysql.jdbc.Driver";
    //取得用户
    private static String USER="root";
    //登录密码
    private static String PASSWORD="1234";
    //静态代码块加载驱动类信息
    static {
    try {
    Class.forName(DRIVER);//将"com.mysql.jdbc.Driver"类的Class类对象加载到运行时内存中
    } catch (ClassNotFoundException e) {
    e.printStackTrace();
    }
    }
    //定义获取Connection对象的方法
    public static Connection getConnection() {
    //定义Connection对象
    Connection conn = null;
    if (conn == null) {
    try {
    conn = DriverManager.getConnection(URL, USER, PASSWORD);
    } catch (SQLException e) {
    e.printStackTrace();
    }
    }
    return conn;
    }
    public static void close(Connection conn) {
    if (conn != null) {
    try {
    conn.close();
    } catch (SQLException e) {
    e.printStackTrace();
    }
    }
    }
    }

    更新数据和事务

    测试封装好的工具类,更新数据

    /**
    1aa6f
    
    * 	更新数据
    * @param count
    * @return
    * @throws SQLException
    */
    public static boolean updateEmp(double count) throws SQLException {
    //取得Connection对象
    Connection conn = ConnectionUtil.getConnection();
    //准备sql语句
    String sql1 = "UPDATE emp SET despoint = despoint-"+ count + "WHERE ename = 'SMITH'";
    String sql2 = "UPDATE emp SET despoint = despoint+"+ count + "WHERE ename = 'cmm'";
    //定义两个变量接收执行sql语句的返回值
    int row1 = 0;
    int row2 = 0;
    //关闭事务自动提交
    conn.setAutoCommit(false);
    //获取发送sql的对象
    try {
    PreparedStatement pst1 = conn.prepareStatement(sql1);
    PreparedStatement pst2 = conn.prepareStatement(sql2);
    row1 = pst1.executeUpdate();
    row2 = pst2.executeUpdate();
    
    //判断数据库修改是否合理
    if (!(row1>0 && row2>0)) {
    conn.rollback();
    }
    //正常执行完成未发生异常,提交事务
    conn.commit();
    } catch (Exception e) {
    //发生异常则事务回滚
    conn.rollback();
    e.printStackTrace();
    }
    ConnectionUtil.close(conn);
    return row1>0 && row2>0;
    }

    在更新数据和事务中需要保证事务的原子性和数据的一致性

    删除数据

    删除单条数据

    /**
    * 	删除单条数据
    * @param id	要删除的数据id
    * @return
    * @throws Exception
    */
    public static boolean deleteById(Integer id) throws Exception {
    //获取connection对象
    Connection conn = ConnectionUtil.getConnection();
    //准备sql语句
    String sql = "DELETE FROM emp WHERE empno = " + id;
    //取得预编译对象
    PreparedStatement pst = conn.prepareStatement(sql);
    //执行sql语句
    int row = pst.executeUpdate();
    //关闭连接
    ConnectionUtil.close(conn);
    return row > 0;
    }

    批量删除数据

    /**
    *  批量删除数据
    * @param ids 要删除的数据的id的集合
    * @return 删除成功返回 true,删除失败返回false
    * @throws Exception
    */
    public static boolean deleteBatch(Set<Integer> ids) throws Exception{
    //获取Connection对象
    Connection conn = ConnectionUtil.getConnection();
    //准备sql语句,使用StringBuffer
    StringBuffer sql = new StringBuffer();
    sql.append("DELETE FROM emp WHERE empno IN (");
    //迭代器遍历集合取得所有的员工编号
    Iterator<Integer> it = ids.iterator();
    while (it.hasNext()) {
    sql.append(it.next()+",");
    }
    sql.delete(sql.length()-1, sql.length());
    sql.append(")");
    //取得预编译对象
    PreparedStatement pst = conn.prepareStatement(sql.toString());
    //执行sql语句
    int row = pst.executeUpdate();
    //关闭连接
    ConnectionUtil.close(conn);
    return row>0;
    }

    查询数据

    根据id查询数据

    /**
    * 	根据id查询数据
    * @param id	要查询的数据的id
    * @throws Exception
    */
    public static void selectById(Integer id) throws Exception {
    //取得连接对象
    Connection conn = ConnectionUtil.getConnection();
    //准备sql语句
    String sql = "SELECT * FROM emp WHERE empno = " + id;
    //取得预编译对象
    PreparedStatement pst = conn.prepareStatement(sql);
    //执行sql语句
    ResultSet rs = pst.executeQuery();
    //判断返回值是否存在,并取出返回值
    if (rs.next()) {
    //写法一
    System.out.println("员工编号:" + rs.getInt(1) + "\r\n姓名:"+rs.getString(2)+"\r\n职位:"+rs.getString(3)+"\r\n直接领导:"+rs.getInt(4)+"\r\n入职日期:"+rs.getDate(5)+
    "\r\n薪资:"+rs.getDouble(6)+"\r\n佣金:"+rs.getDouble(7)+"\r\n部门编号:"+rs.getInt(8));
    //写法二
    System.out.println("员工编号:" + rs.getObject("empno") + "\r\n姓名:"+rs.getObject("ename")+"\r\n职位:"+rs.getObject("job")+"\r\n直接领导:"+rs.getObject("mgr")+
    "\r\n入职日期:"+rs.getObject("hiredate")+"\r\n薪资:"+rs.getObject("sal")+"\r\n佣金:"+rs.getObject("comm")+"\r\n部门编号:"+rs.getObject("deptno"));
    }
    //关闭连接对象
    ConnectionUtil.close(conn);
    }

    模糊查询

    /**
    * 实现模糊分页查询
    * @param kw 模糊查询的关键字
    * @param cp 分页查询所在的页码
    * @param ls 每页的数据量
    * @throws Exception
    */
    public static void selectSplitAll(String kw, int cp, int ls) throws Exception {
    //拼接关键字
    if (kw == null) {
    kw = "";
    }
    kw  = "'%" + kw +"%'";
    //获取连接对象
    Connection conn = ConnectionUtil.getConnection();
    //准备sql语句
    String sql = "SELECT * FROM emp WHERE ename LIKE " + kw + " LIMIT " + (cp-1)*ls + "," + ls;
    //获取预编译对象
    PreparedStatement pst = conn.prepareStatement(sql);
    //执行sql语句
    ResultSet rs = pst.executeQuery();
    while (rs.next()) {
    System.out.println("员工编号:" + rs.getObject("empno") + "\r\n姓名:"+rs.getObject("ename")+"\r\n职位:"+rs.getObject("job")+"\r\n直接领导:"+rs.getObject("mgr")+
    "\r\n入职日期:"+rs.getObject("hiredate")+"\r\n薪资:"+rs.getObject("sal")+"\r\n佣金:"+rs.getObject("comm")+"\r\n部门编号:"+rs.getObject("deptno"));
    System.out.println("--------------------------------");
    }
    //关闭连接
    pst.close();
    rs.close();
    ConnectionUtil.close(conn);
    }
    内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
    标签: