JDBC

一、JBDC

JDBC(Java Database Connective)是一种与不同的数据库连接的操作标准。
由一个类四个接口组成:

  1. java.sql.DriverManagers类
    驱动管理。(注册、加载驱动)
  2. java.sql.Connection接口
    数据库的连接。
    创建Statement接口对象的方法:
Statement createStatement();

创建PreparedStatement接口对象的方法:

PreparedStatement prepareStatement(String sql)
  1. java.sql.Statement接口
    操作sql语句。
    Statement接口对象实现数据库操作的方法:
int	executeUpdate(String sql)			//数据更新
ResultSet executeQuery(String sql)	//数据查询
  1. java.sql.PreparedStatement接口(子接口)
    操作sql语句。
    一系列的setXxx()方法为指定顺序编号的占位符设置具体内容。
int	executeUpdate(String sql)			//数据更新
ResultSet executeQuery(String sql)	//数据查询
  1. java.sql.ResultSet接口:
    返回查询结果集,相当于数据表。

二、JDBC快速入门

package jdbc;

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

/**
 * JDBC快速入门
 */
public class JdbcDemo1 {
    public static void main(String[] args) throws Exception {
        //1.导入驱动jar包
        //2.注册驱动
        Class.forName("com.mysql.jdbc.Driver");
        //3.获取数据库的连接对象
        Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/girls", "root", "799we");
        //4.定义一个sql语句
        String sql = "update boys set userCP = 100 where id = 1";
        //5.获取执行sql的对象Statement
        Statement stmt = conn.createStatement();
        //6.执行sql
        int count = stmt.executeUpdate(sql);
        //7.处理结果
        System.out.println(count);
        //8.释放资源
        stmt.close();
        conn.close();
    }
}

三、练习

  1. 向表中添加一条数据
package jdbc;

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

/**
 * boys表 添加一条数据
 */
public class JdbcDemo2 {
    public static void main(String[] args) {
        Statement stat = null;
        Connection conn = null;
        try {
            //1.注册驱动
            Class.forName("com.mysql.jdbc.Driver");
            //2.定义sql
            String sql = "insert into boys value(null,'渔小翁',7)";
            //3.获取Connection对象
            conn = DriverManager.getConnection("jdbc:mysql:///girls", "root", "799we");
            //4.获取执行sql的对象 Statement
            stat = conn.createStatement();
            //5.执行sql
            int count = stat.executeUpdate(sql);//影响的行数
            //6.处理结果
            System.out.println(count);
            if(count > 0) {
                System.out.println("添加成功");
            } else{
                System.out.println("添加失败");
            }
        } catch (ClassNotFoundException | SQLException e) {
            e.printStackTrace();
        } finally {
            //stat.close();
            //7.释放资源
            //避免空指针异常
            if(stat != null) {
                try {
                    stat.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if(conn != null) {
                try {
                    conn.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }

    }
}

  1. 修改记录
package jdbc;

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

/**
 * boys表,修改记录
 */
public class JdbcDemo3 {
    public static void main(String[] args) {
        Statement stat = null;
        Connection conn = null;
        try {
            Class.forName("com.mysql.jdbc.Driver");
            conn = DriverManager.getConnection("jdbc:mysql:///girls", "root", "799we");
            String sql = "update boys set userCP = 77 where id = 5";
            stat = conn.createStatement();
            int count = stat.executeUpdate(sql);
            System.out.println(count);
            if(count > 0) {
                System.out.println("修改成功");
            } else{
                System.out.println("修改失败");
            }
        } catch (ClassNotFoundException | SQLException e) {
            e.printStackTrace();
        } finally {
            if(stat != null) {
                try {
                    stat.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if( conn != null) {
                try {
                    conn.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

  1. 查询数据
package jdbc;

import domain.boys;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

/*
定义一个方法,查询boys表的数据将其封装为对象,然后装载集合,返回。
 */
public class JdbcDemo8 {
    public static void main(String[] args) {
        List<boys> list = new JdbcDemo8().findAll();
        System.out.println(list);
        System.out.println(list.size());
    }
    /**
     * 查询所有boys对象
     *
     * @return
     */
    public List<boys> findAll() {
        Connection conn = null;
        Statement stmt = null;
        ResultSet rs = null;
        List<boys> list = null;
        try {
            Class.forName("com.mysql.jdbc.Driver");
            conn = DriverManager.getConnection("jdbc:mysql:///girls", "root", "799we");
            String sql = "select * from boys";
            stmt = conn.createStatement();
            rs = stmt.executeQuery(sql);
            //遍历结果集,封装对象,装载集合
            boys boy = null;
            list = new ArrayList<boys>();

            while (rs.next()) {
                //获取数据
                int id = rs.getInt("id");
                String name = rs.getString("boyName");
                int cp = rs.getInt("userCP");
                //创建boys对象,并赋值
                boy = new boys();
                boy.setId(id);
                boy.setBoyName(name);
                boy.setUserCP(cp);

                //装载集合
                list.add(boy);
            }
        } catch (ClassNotFoundException | SQLException e) {
            e.printStackTrace();
        } finally {
            if (rs != null) {
                try {
                    rs.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if (stmt != null) {
                try {
                    stmt.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if (conn != null) {
                try {
                    conn.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
        return list;
    }
}

  1. 登录方法
package jdbc;

import Util.JdbcUtils;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Scanner;

public class JdbcDemo9 {
    public static void main(String[] args) {
        //1.键盘录入,接收用户名和密码
        Scanner sc = new Scanner(System.in);
        System.out.println("请输入用户名:");
        String username = sc.next();
        System.out.println("请输入密码:");
        String password = sc.next();

        //2.调用方法
        boolean flag = new JdbcDemo9().login(username,password);

        //3.判断结果
        if(flag) {
            System.out.println("登录成功");
        } else {
            System.out.println("用户名或密码错误");
        }
    }
    /**
     * 登录方法
     */
    public boolean login (String username,String password) {
        if(username == null || password == null) {
            return false;
        }
        //连接数据库判断是否成功
        Connection conn = null;
        Statement stmt = null;
        ResultSet rs = null;
        //1.获取连接
        try {
            conn = JdbcUtils.getConnection();
            String sql = "select * from user where username = '+username+' and password = '+password+'";
            stmt = conn.createStatement();
            rs = stmt.executeQuery(sql);
            return rs.next();
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            JdbcUtils.close(rs,stmt,conn);
        }
        return false;
    }
}
  1. 事务操作
    事务处理的方法:
void	commit()	//事务提交
void	rollback()	//事务回滚
void	setAutoCommit(boolean autoCommit)	//设置是否为自动提交
package jdbc;

import Util.JdbcUtils;

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

/**
 * 事务操作:转账
 */
public class JdbcDemo10 {
    public static void main(String[] args) {
        Connection conn = null;
        PreparedStatement pstmt1 = null;
        PreparedStatement pstmt2 = null;
        try {
            conn = JdbcUtils.getConnection();

            //开启事务
            conn.setAutoCommit(false);

            String sql1 = "update user set password = password + ? where id = ?";
            String sql2 = "update user set password = password - ? where id = ?";

            pstmt1 = conn.prepareStatement(sql1);
            pstmt2 = conn.prepareStatement(sql2);

            pstmt1.setDouble(1,2);
            pstmt1.setDouble(2,1);
            pstmt2.setDouble(1,2);
            pstmt2.setDouble(2,2);

            pstmt1.executeUpdate();
            pstmt2.executeUpdate();

            //提交事务
            conn.commit();
        } catch (Exception e) {//不管出现什么异常都要进行回滚
            //事务回滚
            try {
                if(conn != null) {
                    conn.rollback();
                }
            } catch (SQLException ex) {
                ex.printStackTrace();
            }
            e.printStackTrace();
        } finally {
            JdbcUtils.close(pstmt1,conn);
            JdbcUtils.close(pstmt2,null);
        }
    }
}

你可能感兴趣的:(JBDC)