代码改变世界

JDBC连接数据库(二)

2018-04-02 01:03  清风软件测试开发  阅读(396)  评论(0编辑  收藏  举报

原文地址https://blog.csdn.net/jq_ak47/article/details/55049639

 

Mysql for java 的JDBC 驱动库安装

1、将下载下来的5.1.40的.zip文件解压缩到合适目录; 
2、将mysql-connector-java-5.1.40-bin.jar文件路径添加到CLASSPATH路径中

D:\Dev\JDBC\mysql-connector-java-5.1.40\mysql-connector-java-5.1.40-bin.jar

 

关于是否需要将这个文件路径添加到CLASSPATH中去,添不添加感觉不是很大事, 
实践:

package db;

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

public class DbDemo {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        ResultSet result = null;
        Connection con = null;
        Statement statement = null;
        try {
            // 第0步:将mysql 的jdbcjar包加入到引用库中来
            // 第一步:将想要连接的数据库驱动类加载到JVM中来,加载过程中并向DriverManager注册Driver
            // 成功加载后,会将Mysql的驱动Driver类的实例注册到DriverManager类中。
            //使得下面我们获取Connection只需要通过DriverManager就可以了。我不需要通过每个数据库具体的Driver。
            Class.forName("com.mysql.jdbc.Driver").newInstance();
            // 第二步,通过DriverManager获取一个和mysql的连接实例con
            String JDBCUrl = "jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8";//
            String userName = "root";
            String password = "1557862201";
            // 接受一个jdbcurl,username,password;
            con = DriverManager.getConnection(JDBCUrl, userName, password);
            // 第三步:通过con连接获取到Statement实例,执行sql语句
            statement = con.createStatement();// statement实例是用于一些不带参数的sql执行,查询,更新,插入,删除操作都可以但是需要构建一个没有占位符的sql字符串
            // 第四步,statement执行sql语句,查询到的结果集到ResultSet实例,简单查询,没有where语句的查询
            result = statement.executeQuery("select * from student");
            // 第五步:从结果集中获取数据
            while (result.next()) {
                // 根据test库中student表格列名读取数据
                int id = result.getInt("id");
                String name = result.getString("_stuName");
                String number = result.getString("_stuNumber");
                String Grade = result.getString(result.findColumn("_stuGrade"));
                String Address = result.getString(result.findColumn("_stuAddress"));
                System.out
                        .println("name= " + name + " number= " + number + " Grade= " + Grade + " Address= " + Address);
            }
            // 插入语句
            // statement.executeUpdate("");
            insert(statement);
            // 执行带参数的查询,有where语句的查询
            int id = 2;
            executeQuery(con, id);
            // 执行更新操作
            updateDate(con, 2);
            delete(con, "XX");// 删除数据行
        } catch (ClassNotFoundException e) {
            // TODO Auto-generated catch block
            System.out.println("找不到驱动程序类 ,加载驱动失败!");
            e.printStackTrace();
        } catch (InstantiationException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (SQLException ex) {
            // TODO Auto-generated catch block
            System.out.println("SQLException: " + ex.getMessage());
            System.out.println("SQLState: " + ex.getSQLState());
            System.out.println("VendorError: " + ex.getErrorCode());
            ex.printStackTrace();
        } finally {
            // 第六步:释放资源
            /**
             * 关闭JDBC对象 操作完成以后要把所有使用的JDBC对象全都关闭,以释放JDBC资源,关闭顺序和声 明顺序相反: 1、关闭记录集
             * 2、关闭声明 3、关闭连接对象
             */
            if (result != null) {// 关闭结果集
                try {
                    result.close();
                } catch (SQLException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                result = null;
            }
            if (statement != null) {// 关闭执行sql语句代码块
                try {
                    statement.close();
                } catch (SQLException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                statement = null;

            }
            if (con != null) {// 关闭连接
                try {
                    con.close();
                } catch (SQLException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                con = null;
            }
        }
    }

    /**
     * 删除一行数据记录
     * 
     * @param con
     * @param name
     * @throws SQLException
     */
    private static void delete(Connection con, String name) throws SQLException {
        // TODO Auto-generated method stub

        System.out.println("delete begin");
        Statement statement = con.createStatement();
        String delete = "delete from student where _stuName= " + "'" + name + "'";
        System.out.println(delete);
        statement.executeUpdate(delete);
        if (statement != null)
            statement.close();
        statement = null;
        System.out.println("delete end");
    }

    /**
     * sql更新数据记录
     * 
     * @param con
     * @param id
     * @throws SQLException
     */
    private static void updateDate(Connection con, int id) throws SQLException {
        // TODO Auto-generated method stub
        System.out.println("update begin");
        PreparedStatement statement = null;
        ResultSet result = null;
        String name = "'mm'";
        String update = "update student set _stuName= " + name + "where id= ?";
        statement = con.prepareStatement(update);
        statement.setInt(1, id);

        statement.executeUpdate();
        if (result != null)
            result.close();
        result = null;
        if (statement != null)
            statement.close();
        statement = null;
        System.out.println("update end");
    }

    /**
     * 带参数的查询
     * 
     * @param con
     * @param id
     * @throws SQLException
     */
    private static void executeQuery(Connection con, int id) throws SQLException {
        System.out.println("begin");
        // TODO Auto-generated method stub
        PreparedStatement statement = null;
        ResultSet result;
        String query = "select * from student where id = ? and _stuName = ?";

        statement = con.prepareStatement(query);
        statement.setInt(1, id);// 第一个占位符的参数
        statement.setString(2, "Cindy");// 第二个占位符的参数
        result = statement.executeQuery();
        while (result.next()) {
            id = result.getInt("id");
            String name = result.getString("_stuName");
            String number = result.getString("_stuNumber");
            String Grade = result.getString(result.findColumn("_stuGrade"));
            String Address = result.getString(result.findColumn("_stuAddress"));
            System.out.println("有参数的查询");
            System.out.println("name= " + name + " number= " + number + " Grade= " + Grade + " Address= " + Address);
            System.out.println("带参数查询成功");
        }
        if (result != null)
            result.close();
        result = null;
        if (statement != null)
            statement.close();
        statement = null;
        System.out.println("end");
    }

    /**
     * 进行插入数据行
     * 
     * @param statement
     * @throws SQLException
     */
    private static void insert(Statement statement) throws SQLException {
        // TODO Auto-generated method stub
        String update = "insert low_priority into student(_stuName, _stuNumber, _stuGrade, _stuAddress)"
                + "values('XX',2100120,'大三','兴国县')";// 降低insert的执行优先级,同理update,delete操作也是一样的
        statement.executeUpdate(update);
        System.out.println("insert successfully");
    }

}