Java database development (1) - JDBC connection database

1. MySQL database

1. Create a database
CREATE DATABASE jdbc CHARACTER SET 'utf8';
2. Build a table
CREATE TABLE user  (
  id int(10) NOT NULL AUTO_INCREMENT,
  userName varchar(20) NOT NULL,
  PRIMARY KEY (id)
);
3. Add data

2. Connect to MySQL database through JDBC

1.JDBC URL


2.Statement

boolean execute(String SQL) : Returns a boolean value of true if the ResultSet object can be retrieved, false otherwise. When you need to use true dynamic SQL, you can use this method to execute SQL DDL statements.
int executeUpdate(String SQL) : Returns the number of rows affected by the execution of the SQL statement. Use this method to execute a SQL statement in the hope of getting some number of rows affected, for example, an INSERT, UPDATE or DELETE statement.
ResultSet executeQuery(String SQL) : Returns a ResultSet object. Use this method when you want to get a result set, just like you would with a SELECT statement.

3. ResultSet object

Execute the SQL statement through the executeQuery() method of the Statement object to get the ResultSet object

4. Specific steps and codes

static final String JDBC_DRIVER = "com.mysql.cj.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost:3306/jdbc?useSSL=false";
static final String USER = "root";
static final String PASSWORD = "123456";

public static void hello() throws ClassNotFoundException {
    Connection conn = null;
    Statement stmt = null;
    ResultSet rs = null;

    //1.装载驱动程序
    Class.forName(JDBC_DRIVER);
    //2.建立数据库连接
    try {
        conn = DriverManager.getConnection(DB_URL, USER, PASSWORD);
        //3.执行SQL语句
        stmt = conn.createStatement();
        rs = stmt.executeQuery("select userName from user");
        //4.获取执行结果
        while (rs.next()) {
            System.out.println("Hello " + rs.getString("userName"));
        }
    } catch (SQLException e) {
        e.printStackTrace();
    } finally {
        //5.清理环境
        try {
            if (conn != null) conn.close();
            if (stmt != null) stmt.close();
            if (rs != null) rs.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324983119&siteId=291194637