获得某表所有列的信息:
String sql = select * from tname//tname为某一表名
Connection conn = ....
Statement st = conn.createStatement()
ResultSet rs = st.rs = st.executeQuery(sql)
ResultSetMetaData rsmd = rs.getMetaData()
int colcount = rsmd.getColumnCount()//取得全部列数
for(int i=0i<colcounti++){
String colname = rsmd.getColumnName(i)//取得全部列名
}
以上为某表字段具体查询,如果是查询表的信息,如在mysql服务器上那样的查询结果的话,可以用一下代码:
ResultSet.executeQuery("show tables")可以的到所有的表信息。
ResultSet.executeQuery("describe tname")可以得到表的字段信息。//tname为表名
import java.sql.Connectionimport java.sql.DriverManager
import java.sql.ResultSet
import java.sql.ResultSetMetaData
import java.sql.Statement
import java.util.Hashtable
public class GetDBFiled {
public static void conn() {
String driver = "com.mysql.jdbc.Driver"
String url = "jdbc:mysql://localhost:3306/databaseName"
String user = "root"
String password = "密码"
try {
Class.forName(driver)
Connection conn = DriverManager.getConnection(url, user, password)
if (!conn.isClosed()) {
String sql = "select * from pic"
System.out.println("Succeeded connecting to the Database!")
Statement statement =conn.createStatement()
ResultSet rs = statement.executeQuery(sql)
if (rs.next()) {
// 得到ResultSetMetaData
ResultSetMetaData rsmd = rs.getMetaData()
System.out.println(rsmd.getColumnCount())
for (int i = 1 i <= rsmd.getColumnCount() i++) {
Hashtable hst = new Hashtable()
// 把字段名放入Name
String name = String.valueOf(rsmd.getColumnLabel(i))
hst.put("Name", name)
// 把字段类型放入Type
String type = String.valueOf(rsmd.getColumnType(i))
hst.put("Type", type)
System.out.println(hst.get("Name")+" "+hst.get("Type"))
}
}
}
} catch (Exception e) {
System.out.println("出现异常")
}
}
}
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)