JDBC的详细插入操作

package com.jdbc;

import java.sql.*;

public class JdbcTestTwo {
    private static String url = "jdbc:mysql://localhost:3306/jdbc?serverTimezone=Asia/Shanghai" +
            "&?useUnicode=true&characterEncoding=utf8&useSSL=false";
    private static String username = "root";
    private static String password = "7896";
    public static void main(String[] args) throws ClassNotFoundException, SQLException {
        // 1、加载驱动
        Class.forName("com.mysql.jdbc.Driver");
        // 2、连接数据库,代表数据库
        Connection connection = DriverManager.getConnection(url, username, password);
        // 3、编写SQL
        String sql = "insert into users(id, name, password, email, birthday) VALUES (?,?,?,?,?)"; //删除
        // 4、向数据库发送sql的对象Statement PreparedStatement: CRUD
        PreparedStatement preparedStatement = connection.prepareStatement(sql);
        preparedStatement.setInt(1,10);
        preparedStatement.setString(2,"java");
        //给第三个占位符?的值赋值为123456;
        preparedStatement.setString( 3,  "123456");
        //给第四个占位符?的值赋值为1;
        preparedStatement.setString( 4, "[email protected]");
        //给第五个占位符?的值赋值为1;
        preparedStatement.setDate( 5, new Date( new java.util.Date().getTime()));
        // 执行插入操作 受影响的行数
        int update = preparedStatement.executeUpdate();
        if(update > 1){
            System.out.println("插入成功!");
        }
        // 5、执行查询SQL
        JdbcTestTwo.QueryDataTable();
        preparedStatement.close();
        connection.close();
    }

    public static void QueryDataTable() throws ClassNotFoundException, SQLException {
        // 1、加载驱动
        Class.forName("com.mysql.jdbc.Driver");
        // 2、连接数据库,代表数据库
        Connection connection = DriverManager.getConnection(url, username, password);
        // 3、编写查询SQL
        String QuerySql = "select * from users";
        // 4、向数据库发送sql的预处理对象Statement PreparedStatement: CRUD
        PreparedStatement preparedStatement = connection.prepareStatement(QuerySql);
        // 5、执行查询SQL,返回一个ResultSet
        ResultSet resultQuerySet = preparedStatement.executeQuery();
        while(resultQuerySet.next()){
            System.out.println("id="+resultQuerySet.getObject("id"));
            System.out.println("name="+resultQuerySet.getObject("name"));
            System.out.println("password="+resultQuerySet.getObject("password"));
            System.out.println("email="+resultQuerySet.getObject("email"));
            System.out.println("birthday="+resultQuerySet.getObject("birthday"));
        }
        resultQuerySet.close();
        preparedStatement.close();
        connection.close();
    }
}

你可能感兴趣的:(java,后端,数据库,java,后端)