Detailed overview and JDBC programming steps

A, JDBC Overview

Java Database Connectivity: Database Connectivity, is an executable SQL statement API.

JDBC is oriented programming interface Typical applications: relational database systems and diverse types (such as MySQL, DB2, Oracle), in order to achieve unity simplify development, Sun has developed a standard set of API (the interface), different vendors realize that basis JDBC database program developed cross-platform execution , the driver only needs to use different databases.

Here Insert Picture Description

Most database systems have the appropriate JDBC driver, when connected to a particular database, you must have the appropriate database drivers.

Two, JDBC programming steps (to MySQL for example)

1, into jar package

IDEA, import the JDBC driver jar package corresponding to the project, and by add libraryadding to the workspace.

2, load the database driver

Load database driver, commonly used class Class forName(驱动类全类名)loading driving, for example, a method of driving loaded MySQL:

Class.forName("com.mysql.jdbc.Driver");

Note that the latest JDBC driver class driver has been automatically registered by SPI, under the META-INF jar in this case / services directory contains java.sql.Driver file has been specified JDBC driver class, so In this case, in fact, this step can be omitted.

Here Insert Picture Description

3, obtained by DriverManager Connection object

Using DriverManagerstatic methods class public static Connection getConnection(String url,String user, String password)acquiring connection object Connection.

The arguments: database URL, user name user, password is password.

  • Way of writing database URL:jdbc:mysql://服务器名或IP地址:端口号/数据库名[?参数名=参数值]

    Connection conn = DriverManager.getConnection( "jdbc:mysql://localhost:3306/mydb2", "root", "123456");
    
  • If the server is local in MySQL can be abbreviated as follows:

    Connection conn = DriverManager.getConnection( "jdbc:mysql://localhost:3306/mydb2", "root", "123456");
    

另外getConnection还有个重载方法:public static Connection getConnection(String url,java.util.Properties info),将user和password存储到Properties对象中,传入方法即可。

Properties prop = new Properties();
prop.setProperty("user","root");
prop.setProperty("password","123456")

DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb2",prop);

3、定义SQL语句

String sql = "update orders set price = 500 where id = 1";//普通的sql语句

//如果需要执行某些相似的sql语句多次,只有某个地方有改动,可以使用带占位符的sql语句
String sql = "select * from user where username = ? and password = ?";//带占位符的sql语句

4、利用Connection创建Statement对象

//创建最基本的Statement对象
Statement statement = conn.createStatement();

//创建一个预编译sql语句的PreparedStatement对象,后者是前者的子接口。使用时需要将sql语句占位符部分进行填充。
PreparedStatement prs = conn.prepareStatement(sql);

Statement与PreparedStatement:

  • 在执行多次相似的sql语句时,PreparedStatement预编译SQL语句性能更好。

  • PreparedStatement无需凭借SQL语句,编程更加简单(ps:确实简单)。

  • PreparedStatement可以防止SQL注入。

    //SQL注入的例子:
    String sql = "select * from user where username = '"+username+"'and password = '"+password+"'";
    resultSet = statement.executeQuery(sql);
    return resultSet.next();
    

    当我用Statement对象执行拼接完成之后的SQL语句,目的是为了判断是否传入正确的用户名和密码。这时,如果随便输入不存在的用户名dede,密码输入:' or true or ',这时SQL注入之后就会变成下面这个鬼样子:

    select * from user where username = 'dede'and password = ''or true or '';
    

    相当于直接输入了true,非常不合理,而PreparedStatement可以避免SQL注入:

    //PreparedStatement防止SQL注入
    String sql = "select * from user where username = ? and password = ?";
    preparedStatement.setString(1,username);
    preparedStatement.setString(2,password);
    resultSet = preparedStatement.executeQuery();
    
    

5、利用Statement执行SQL语句

无论是Statement还是它的子接口对象,都拥有执行SQL语句的方法,下面是比较重要的几个:

  • boolean excute():可以执行任何的SQL语句,但是比较麻烦,通常不用。(这个方法在子接口里是没有的嗷),如果部清楚SQL语句的类型,可以使用该方法。
  • int executeUpdate():用于执行DML和DDL语句,返回结果是受影响的行数。
//定义sql语句
String sql = "update orders set price = 500 where id = 1";
//获取执行sql的对象 Statement
Statement stmt = conn.createStatement();
//执行sql
int count = stmt.executeUpdate(sql);

  • ResultSet executeQuery():只能执行查询语句,返回结果是一个ResultSet结果集。
PreparedStatement preparedStatement = null;
//定义sql语句
String sql = "select * from user where username = ? and password = ?";
//获取PreparedStatement对象
preparedStatement = conn.prepareStatement(sql);
//给对应的占位符赋值,如果不清楚参数类型可以使用setObject()传入参数
preparedStatement.setString(1,username);
preparedStatement.setString(2,password);
//执行查询语句,获取结果集
ResultSet resultSet = preparedStatement.executeQuery();

6、操作ResultSet对象

明确一点,ResultSet对象是通过excuteQuery执行查询语句的结果。原理类似于迭代器,通过指针的移动来获取值。

典型的方法:

  • next (): Before the start pointer points to the first row, the pointer is moved downward, it returns a boolean value, whether the recording on behalf of the back, there returns true, no returns false. Therefore, the recording can be directly determines whether there is a ResultSet.next();judgment.

  • getXxx (): the value of the specified row to acquire, a particular column. There are many overloaded methods include: passing specified number of columns (starting from 1, as getInt(1)representative for the first column line INT value), specified parameters (pass column name, such as getInt("id")obtaining diverted id field value).

//打印所有记录
while(resultSet.next()) {
    //获取数据
    int id = resultSet.getInt(1);
    String product = resultSet.getString("product");
    int price = resultSet.getInt("price");

    System.out.println(id + "--" + product + "--" + price);
}

7, database recovery resources

Recovery of database resources in two ways:

Connection, Statement, ResultSet inherit AutoCloseable interface that can be used Java7 of try-with-resourcesthe automatic shut resources try statement to close:

    public static void main(String[] args) throws Exception {
        Class.forName("com.mysql.jdbc.Driver");
        try (
                Connection conn = DriverManager.getConnection(
                        "jdbc:mysql://localhost:3306/mydb2", "root", "123456");
                Statement stmt = conn.createStatement())
        {
            String sql = "update orders set price = 500 where id = 1";
            int count = stmt.executeUpdate(sql);
            System.out.println(count);
        }
    }

There is the traditional try ...... catch statement:

    public static void main(String[] args){
        Connection conn = null;
        Statement stmt = null;
        try {
            Class.forName("com.mysql.jdbc.Driver");
            conn = DriverManager.getConnection(
                    "jdbc:mysql://localhost:3306/mydb2", "root", "123456");
            stmt = conn.createStatement();
            String sql = "update orders set price = 500 where id = 1";
            int count = stmt.executeUpdate(sql);
            System.out.println(count);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            //避免空指针异常
            if(stmt!=null){
                try {
                    stmt.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if (conn!=null){
                try {
                    conn.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
    }

Reference: "crazy Java handouts"

Published 85 original articles · won praise 67 · views 6772

Guess you like

Origin blog.csdn.net/Sky_QiaoBa_Sum/article/details/104723284