本文主要是介绍JDBC获取表的各列的基本信息,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
很多时候,我们需要查看数据库中的数据表的每个列或部分列的属性,例如列名,数据类型,大小等,以下代码通过Java实现类获取指定表的各列信息,并将信息存储到ArrayList中。
public class MySQLHandle {//mysql驱动包名private static final String DRIVER_NAME = "com.mysql.jdbc.Driver";//数据库连接地址private static final String URL = "jdbc:mysql://localhost:3306/test";//用户名private static final String USER_NAME = "root";//密码private static final String PASSWORD = "rootroot";//数据库连接对象private static Connection connection;public static void main(String[] args) {}static {try {//加载mysql的驱动类Class.forName(DRIVER_NAME);} catch (Exception e) {e.printStackTrace();}}//构造函数,包括连接数据库等操作public MySQLHandle(){try {//加载mysql的驱动类Class.forName(DRIVER_NAME);//获取数据库连接connection = DriverManager.getConnection(URL, USER_NAME, PASSWORD);} catch (Exception e) {e.printStackTrace();connection = null;}}//带参数构造函数,用于指定参数连接数据库public MySQLHandle(String Database,String User,String Password){try {//加载mysql的驱动类Class.forName(DRIVER_NAME);//获取数据库连接connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/"+Database, User, Password);} catch (Exception e) {e.printStackTrace();connection = null;}}public Connection getConnection(){return connection;}public static void ReleaseConnect(){if (connection != null) {try {connection.close();} catch (SQLException e) {e.printStackTrace();}}}/*** @方法描述:执行Select查询语句* @param query 待执行的SQL查询语句* @return ResultSet 从数据库中查询的结果集*/public ResultSet ExecuteSQL(String query){ResultSet rs = null;try {if (query == null)return null;else {PreparedStatement prepareStatement = connection.prepareStatement(query);rs = prepareStatement.executeQuery();}}catch (Exception e) {e.printStackTrace();return null;}return rs;}/*** @方法描述:获取数据表的所有列属性* @param TableName 查找的数据表名* @return 返回列属性*/public ArrayList<ArrayList<String>> geyAttributesFromTable(String TableName){String sql="SELECT * FROM "+TableName+" limit 1";ArrayList<ArrayList<String>> list = new ArrayList();try{ResultSet rs=ExecuteSQL(sql);ResultSetMetaData rs_metaData = rs.getMetaData();while (rs.next()) {int count = rs_metaData.getColumnCount();for (int i=0; i<count; i++) {ArrayList<String> subList=new ArrayList<>(3);// 得到列的名称String columnName = rs_metaData.getColumnLabel(i + 1);//得到列的大小String columnSize =String.valueOf(rs_metaData.getColumnDisplaySize(i+1));//得到列的数据类型String columnType = rs_metaData.getColumnTypeName(i+1);subList.add(columnName);subList.add(columnType);subList.add(columnSize);list.add(subList);}}rs.close();return list;}catch (Exception e) {e.printStackTrace();return list;}}
}
这篇关于JDBC获取表的各列的基本信息的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!