灵活的传入sql语句,和sql语句的参数
报错:java.sql.SQLException: Parameter metadata not available for the given statement
原因不明
package cn.itcast.jdbc;
import java.sql.Connection;
import java.sql.Date;
import java.sql.ParameterMetaData;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class ParameterMetaTest {
public static void main(String[] args) throws SQLException{
String sql = "select name,birthday from user where name =? and birthday<? and money>?";
Object[] params = new Object[]{"list", new Date(System.currentTimeMillis()), 100f};
ParameterMetaTest.read(sql,params);
}
//灵活的传入语句和参数
public static void read(String sql, Object[] params) throws SQLException{
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
try {
conn = JdbcUtils.getConnection();
ps = conn.prepareStatement(sql);
//可用于获取关于 PreparedStatement 对象中每个参数标记的类型和属性信息的对象
ParameterMetaData pmd = ps.getParameterMetaData();
int count = pmd.getParameterCount();
for(int i=1; i<=count; i++){
System.out.println(pmd.getParameterClassName(i));
System.out.println(pmd.getParameterType(i));
System.out.println(pmd.getParameterTypeName(i));
ps.setObject(i, params[i-1]);
}
rs = ps.executeQuery();
while(rs.next()){
System.out.println(rs.getObject("name"));
System.out.println(rs.getObject("birthday"));
}
} catch (SQLException e) {
e.printStackTrace();
}finally{
JdbcUtils.free(rs, ps, conn);
}
}
}
本文介绍了一个Java JDBC示例,展示了如何使用PreparedStatement来执行带有参数的SQL查询,并通过ParameterMetaData获取参数的相关信息。但在运行过程中遇到了java.sql.SQLException: Parametermetadata not available for the given statement的错误。

被折叠的 条评论
为什么被折叠?



