针对customers表的查询操作举例
Jihongchang(讨论 | 贡献)2022年12月17日 (六) 10:55的版本
https://www.bilibili.com/video/BV1eJ411c7rf?p=17
| Java 类型 | SQL 类型 | 
|---|---|
| boolean | BIT | 
| byte | TINYINT | 
| short | SMALLINT | 
| int | INTEGER | 
| long | BIGINT | 
| String | CHAR, VARCHAR, LONGVARCHAR | 
| byte array | BINARY,,VAR BINARY | 
| java.sql.Date | DATE | 
| java.sql.Time | TIME | 
| java.sql.Timestamp | TIMESTAMP | 
import io.github.jihch.bean.Customer;
import io.github.jihch.util.JDBCUtils;
import org.junit.Test;
import java.sql.*;
/**
 * 针对于 Customers 表的查询操作
 */
public class CustomerForQuery {
    @Test
    public void testQuery1() {
        String sql = "select id, name, email, birth from customers where id = ?";
        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet resultSet = null;
        try {
            conn = JDBCUtils.getConnection();
            ps = conn.prepareStatement(sql);
            ps.setObject(1, 2);
            //执行,并返回结果集
            resultSet = ps.executeQuery();
            //处理结果集
            if (resultSet.next()) { //next():判断结果集的下一条是否有数据,如果有数据返回 true,并指针下移;如果返回 false,指针不会下移
                //获取当前这条数据的各个字段值
                int id = resultSet.getInt(1);
                String name = resultSet.getString(2);
                String email = resultSet.getString(3);
                Date birth = resultSet.getDate(4);
                //方式一:
//            System.out.println("id = " + id+", name = " + name + ", email = " + email + ", birth = " + birth);
                //方式二:
//            Object[] data = new Object[]{id, name, email, birth};
                //方式三:将数据封装为一个对象(推荐)
                Customer customer = new Customer(id, name, email, birth);
                System.out.println(customer);
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            JDBCUtils.closeResource(conn, ps, resultSet);
        }
    }//end testQuery1
}