JDBC 处理查询

  1. 加载驱动程序
  2. 建立连接
  3. 创建Statement对象
  4. 执行查询

一般查询

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

public class testStatement {

    public static void main(String[] args) {
        String url="jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf8";

        try {
            //加载驱动程序
            Class.forName("com.mysql.jdbc.Driver");
            //建立连接
            Connection con = DriverManager.getConnection(url, "root", "123456");
            //创建 Statement 对象
            Statement st = con.createStatement();
            //设置选项
            st.setMaxRows(100);
            //执行查询
            ResultSet rs = st.executeQuery("SELECT * FROM employee");
            //获取选项设置情况
            //System.out.println("Row length limit:"+st.getMaxFieldSize());
            //Access 数据库不支持 getMaxFieldSize() 方法
            System.out.println("ResultSet MaxRows:"+st.getMaxRows());
            System.out.println("Query Time Out:"+st.getQueryTimeout());
            //取出数据
            String name;
            int id;
            while(rs.next()) {
                id = rs.getInt("employee_id");
                name = rs.getString("employee_name");
                System.out.println("ID:"+id+"\tNAME:"+name);
            }
            //关闭对象
            st.close();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

}

参数查询

//创建 PreparedStatement 对象
String sqlStr = "SELECT * FROM employee WHERE employee_age>? ";
PreparedStatement ps = con.prepareStatement(sqlStr);
ps.setInt(1, 25);
//执行查询,获取结果集
ResultSet rs = ps.executeQuery();

存储过程

//创建CallableStatement
CallableStatement cs = con.prepareCall("{call testquery()}");
//执行查询,获取结果集
ResultSet rs = cs.executeQuery();
原创文章 45 获赞 151 访问量 11万+

猜你喜欢

转载自blog.csdn.net/u010697681/article/details/79035687