JDBC 处理查询
程序员文章站
2024-03-01 16:57:28
...
- 加载驱动程序
- 建立连接
- 创建Statement对象
- 执行查询
一般查询
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();