Statement执行DQL语句(查询操作)

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;

import org.junit.Test;

import util.JdbcUtil;

/**
 * 使用Statement执行DQL语句(查询操作)
 * @author APPle
 */
public class Demo4 {

    @Test
    public void test1(){
        Connection conn = null;
        Statement stmt = null;
        try{
            //获取连接
            conn = JdbcUtil.getConnection();
            //创建Statement
            stmt = conn.createStatement();
            //准备sql
            String sql = "SELECT * FROM student2";
            //执行sql
            ResultSet rs = stmt.executeQuery(sql);
        
            
            //遍历结果
            while(rs.next()){
                int id = rs.getInt("id");
                String name = rs.getString("name");
                String gender = rs.getString("gender");
                System.out.println(id+","+name+","+gender);
            }
            
        }catch(Exception e){
            e.printStackTrace();
            throw new RuntimeException(e);
        }finally{
            JdbcUtil.close(conn, stmt);
        }
    }
}
Jdbc程序中的Statement对象用于向数据库发送SQL语句, Statement对象常用方法:
executeQuery(String sql) :用于向数据发送查询语句。
executeUpdate(String sql):用于向数据库发送insert、update或delete语句
execute(String sql):用于向数据库发送任意sql语句
addBatch(String sql) :把多条sql语句放到一个批处理中。
executeBatch():向数据库发送一批sql语句执行。 
原文地址:https://www.cnblogs.com/linst/p/5868341.html