JDBC学习笔记(14):数据库的元数据信息与参数的元数据信息
数据库的元数据信息:
1 package com.xxyh.jdbc; 2 import java.sql.DatabaseMetaData; 3 import java.sql.SQLException; 4 public class DBMD { 5 6 public static void main(String[] args) throws SQLException { 7 java.sql.Connection conn = JdbcUtils.getConnection(); 8 DatabaseMetaData dbmd = conn.getMetaData(); 9 // dbmd.getConnection(); 10 System.out.println("数据库连接:" + dbmd.getConnection()); 11 System.out.println("驱动名:" + dbmd.getDriverName()); 12 System.out.println("数据库名:" + dbmd.getDatabaseProductName()); 13 System.out.println("数据库版本号:" + dbmd.getDatabaseProductVersion()); 14 System.out.println("是否支持事务:" + dbmd.supportsTransactions()); 15 } 16 }
参数的元数据信息
1 package com.xxyh.jdbc; 2 import java.sql.Connection; 3 import java.sql.ParameterMetaData; 4 import java.sql.PreparedStatement; 5 import java.sql.ResultSet; 6 import java.sql.SQLException; 7 public class ParameterMetaTest { 8 9 public static void main(String[] args) throws SQLException { 10 read("select * from user where name=? and birthday<? and money>?", null); 11 } 12 13 static void read(String sql, Object[] params) throws SQLException { 14 Connection conn = null; 15 PreparedStatement ps = null; 16 ResultSet rs = null; 17 18 try { 19 conn = JdbcUtils.getConnection(); 20 ps = conn.prepareStatement(sql); 21 ParameterMetaData pmd = ps.getParameterMetaData(); 22 int count = pmd.getParameterCount();// 获取参数个数 23 for (int i = 1; i <= count; i++) { 24 System.out.print(pmd.getParameterClassName(i)+"\t"); 25 System.out.print(pmd.getParameterType(i)+"\t"); 26 System.out.println(pmd.getParameterTypeName(i)); 27 } 28 } finally { 29 JdbcUtils.close(rs, ps, conn); 30 } 31 } 32 }
1 package com.xxyh.jdbc; 2 import java.sql.Connection; 3 import java.sql.Date; 4 import java.sql.PreparedStatement; 5 import java.sql.ResultSet; 6 import java.sql.SQLException; 7 public class ParameterMetaTest { 8 9 public static void main(String[] args) throws SQLException { 10 Object[] params = new Object[]{"lisi", new Date(System.currentTimeMillis()), 100f}; 11 read("select * from user where name=? and birthday < ? and money > ?", params); 12 } 13 14 static void read(String sql, Object[] params) throws SQLException { 15 Connection conn = null; 16 PreparedStatement ps = null; 17 ResultSet rs = null; 18 19 try { 20 conn = JdbcUtils.getConnection(); 21 ps = conn.prepareStatement(sql); 22 // ParameterMetaData pmd = ps.getParameterMetaData(); 23 // int count = pmd.getParameterCount();// 获取参数个数 24 for (int i = 1; i <= params.length; i++) { 25 ps.setObject(i, params[i-1]); 26 } 27 28 rs = ps.executeQuery(); 29 30 while (rs.next()) { 31 System.out.println(rs.getInt("id") + "\t" 32 + rs.getString("name") + "\t" 33 + rs.getDate("birthday") + "\t" 34 + rs.getFloat("money")); 35 } 36 } finally { 37 JdbcUtils.close(rs, ps, conn); 38 } 39 } 40 }
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。