Java数据库开发(一)之——JDBC连接数据库

一、MySQL数据库

1.创建数据库
CREATE DATABASE jdbc CHARACTER SET 'utf8';
2.建表
CREATE TABLE user  (
  id int(10) NOT NULL AUTO_INCREMENT,
  userName varchar(20) NOT NULL,
  PRIMARY KEY (id)
);
3.添加数据

二、通过JDBC连接MySQL数据库

1.JDBC URL

2.Statement
  • executeQuery(String sql) :用于向数据发送查询语句。
  • executeUpdate(String sql):用于向数据库发送insert、update或delete语句
  • execute(String sql):用于向数据库发送任意sql语句
  • addBatch(String sql) :把多条sql语句放到一个批处理中。
  • executeBatch():向数据库发送一批sql语句执行。
3.ResultSet对象

通过Statement对象的executeQuery()方法执行SQL语句,得到ResultSet对象

  • next():移动到下一行
  • Previous():移动到前一行
  • absolute(int row):移动到指定行
  • beforeFirst():移动resultSet的最前面。
  • afterLast() :移动到resultSet的最后面
4.具体步骤及代码

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();
        }
    }
}

你可能感兴趣的:(Java,MySQL)