通过java程序如何在已知表明的情况下获得数据库中该张表的表结构?

2024-12-22 18:06:07
推荐回答(2个)
回答1:

public static void getConnAndTableStruct(){
Connection connection = null;
PreparedStatement pstmt = null;
ResultSetMetaData rsmd = null;
try {
//mysql连接
Class.forName("org.gjt.mm.mysql.Driver");
connection = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/test", "root", "root");
//oracle连接
// Class.forName("oracle.jdbc.driver.OracleDriver");
// String url="jdbc:oracle:thin:@173.10.2.11:1521:test";
// connection=DriverManager.getConnection(url,"root","root");

pstmt = (PreparedStatement) connection.prepareStatement("select * from user");
pstmt.execute(); //这点特别要注意:如果是Oracle而对于mysql可以不用加.
rsmd = (ResultSetMetaData) pstmt.getMetaData();
className="User";
tableName="user";
for (int i = 1; i < rsmd.getColumnCount() + 1; i++) {
Table table=new Table();
table.setColumnName(rsmd.getColumnName(i));
table.setColumnType(rsmd.getColumnClassName(i).substring(rsmd.getColumnClassName

(i).lastIndexOf(".")+1));
tables.add(table);
System.out.println(rsmd.getColumnName(i)+ " " +rsmd.getColumnTypeName(i)
+" " +rsmd.getColumnClassName(i)+ " "+rsmd.getTableName(i));
}
}
catch (ClassNotFoundException cnfex) {
cnfex.printStackTrace();
}
catch (SQLException sqlex) {
sqlex.printStackTrace();
}

}

回答2:

在java端写sql语句啊,select * from tablename
然后execute就行