[JDBC Notes] Quick Start to JDBC

JDBC:java database connectivity java connects to the database.

sun company defines the rules (interfaces) that operate all relational databases .

Using unified java code, you can operate all relational databases.

Each database vendor implements the interface and provides the database driver jar package . The actual code executed is the implementation class in the driver jar package.


step:

1. Import the driver jar package

Build directory -> stick package -> add as Library

2. Register the driver (can not write)

3. Get the connection object Connection of the database

4. Define sql

5. Get the object Statement that executes the sql statement

6. Execute sql, execute the return result

7. Processing results

8. Release resources


DriveManager: Drive management object

Features:

Register the driver (tell the program which database driver jar package should be used)

static void registerDriver(Driver driver): register the given driver DriveManager

写法:Class.forName("com.mysql.jdbc.Driver");

Principle: By viewing the source code, it is found that there is a static code block in com.mysql.jdbc.Driver, and the registerDriver method of DriveManager is called

(After mysql 5, there is no need to register the driver, the driver is automatically registered, it is recommended to write it)

get database connection

static Connection getConnection(String url,String user,String password)

url: specifies the path of the connection 

Syntax: jdbc:mysql://ip address:port number/database name

If the connection is to the local mysql server, and the default port of the mysql service is 3306. The url can be abbreviated as:

jdbc:mysql:///database name

Connection: database connection object

Get the object that executes sql:

Statement createStatement()

PrepareStatement prepareStatement(String sql)

Manage affairs:

*Open transaction

setAutoCommit(boolean autoCommit): Call this method to set the parameter to false, that is, to open the transaction

* Commit transaction

commit()

* rollback transaction

rollback()

Statement: used to execute static sql statements

Execute sql:

int executeUpdate(String sql): Execute DML (insert, update, delete) statements, DDL (create, delete) statements

Return value: the number of rows affected

The success of the DML statement can be judged by the number of affected rows (>0)

ResultaSet executeQuery(String sql): execute DQL(select) statement

ResultSet: The result set object, which encapsulates the query results

The cursor starts at the header position

boolean next(): The cursor moves down a row to determine whether there is data

getXxx(): Get data. Xxx represents the data type

getInt,getString,get....

parameter:

Pass in an int representing the column number (starting from 1)

Pass in String representing the name of the column getString("sex")

ResultSet traversal:

JDBC tool class: JDBCUtils (simplified writing)

public class JDBCUtils {
    private static String url;
    private static String user;
    private static String password;
    //配置文件只读取一次,静态代码块
    static{
        //读取资源文件,获取值
        Properties properties=new Properties();
        //加载文件
        try {
            properties.load(new FileReader("src/jdbc.properties"));
            url=properties.getProperty("url");
            user=properties.getProperty("user");
            password=properties.getProperty("password");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    //获取连接
    public static Connection getConnection()  {
        try {
            return DriverManager.getConnection(url,user,password);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }
    //释放资源
    public static void close(Statement st,Connection ct){
        if(st!=null){
            try {
                st.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if(ct!=null){
            try {
                ct.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
    public static void close(ResultSet rs,Statement st,Connection ct){
        if(rs!=null){
            try {
                rs.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        close(st,ct);
    }

}

PreparedStatement: execute sql object

SQL injection problem:

When splicing sql, there are some special sql keywords involved in the splicing of strings, which will cause security problems

Solution: Use PreparedStatement to represent objects and execute precompiled sql statements (parameters use? as placeholders)

When defining the sql parameter to use? as a placeholder

select *from user where username = ? and password = ?

Get the object that executes the sql statement

PrepareStatement pre=Connection.prepareStatement(String sql);

 Assign a value to ?:

setXxx(参数1,参数2)
//参数1:?位置
//参数2:?值

Execute sql: no need to pass sql

 Note: The preparedstatement will be used for additions, deletions and changes in the later stage.

Guess you like

Origin blog.csdn.net/m0_52043808/article/details/123952340