直接上代码package jdbc;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
public class MyTest {
public static void main(String args[]) {
Connection con = null;
try {
// 注册JDBC驱动,JAVA1.5以后 JDBC自动加载驱动了 所以这句代码可以省略;
Class.forName("com.mysql.jdbc.Driver").newInstance();
// 提供地址用户名密码并获得连接对象
con = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/test","root", "");
if (!con.isClosed())
// 连接成功提示
System.out.println("Successfully connected to MySQL server using TCP/IP...");
// 有Connection对象创建PreparedStatement
PreparedStatement ps= con.prepareStatement("select * from orderitem o where o.itemid >?");
// 设置参数,参数索引位置是从1开始(Hibernate参数索引位置是从0开始)
ps.setInt(1, 10);//过滤itemid大于10的记录
ResultSet rs = ps.executeQuery();
// 循环读取结果集的每一行的每一列
while (rs.next()) {
// 打印数据
System.out.print(rs.getString("itemid")+";");
System.out.print(rs.getString("count")+";");
System.out.print(rs.getString("subtotal")+";");
System.out.print(rs.getString("pid")+";");
System.out.println(rs.getString("oid")+";");
}
// 关闭
con.close();
ps.close();
} catch(Exception e) {
System.err.println("Exception: " + e.getMessage());
}
}
}
ResultSet. getMetaData() 获得代表ResultSet对象元数据的ResultSetMetaData对象。/**
* @Method: testParameterMetaData
* @Description: 获取参数元信息
* @Anthor:孤傲苍狼
*
* @throws SQLException
*/
@Test
public void testParameterMetaData() throws SQLException {
Connection conn = JdbcUtils.getConnection();
String sql = "select * from user wherer name=? and password=?";
//将SQL预编译一下
PreparedStatement st = conn.prepareStatement(sql);
ParameterMetaData pm = st.getParameterMetaData();
//getParameterCount() 获得指定参数的个数
System.out.println(pm.getParameterCount());
//getParameterType(int param):获得指定参数的sql类型,MySQL数据库驱动不支持
System.out.println(pm.getParameterType(1));
JdbcUtils.release(conn, null, null);
}
参考文章:
Statement
深入 理解 Statement 和 PreparedStatement