用什么代码获取数据库表
时间: 2024-03-05 20:49:45 浏览: 89
获取数据库表的代码可以根据不同的编程语言和数据库类型而有所不同,以下是几个常见的示例:
1. Python获取MySQL数据库表:
```
import mysql.connector
# 连接数据库
cnx = mysql.connector.connect(user='username', password='password', host='localhost', database='database_name')
# 获取表名
cursor = cnx.cursor()
cursor.execute("SHOW TABLES")
# 遍历表名
for table_name in cursor:
print(table_name)
# 关闭连接
cursor.close()
cnx.close()
```
2. Java获取Oracle数据库表:
```
import java.sql.*;
// 连接数据库
Connection conn = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:orcl", "username", "password");
// 获取表名
DatabaseMetaData metaData = conn.getMetaData();
ResultSet rs = metaData.getTables(null, null, null, new String[] {"TABLE"});
// 遍历表名
while (rs.next()) {
String tableName = rs.getString("TABLE_NAME");
System.out.println(tableName);
}
// 关闭连接
rs.close();
conn.close();
```
3. PHP获取SQL Server数据库表:
```
$serverName = "localhost";
$connectionInfo = array("Database"=>"database_name", "UID"=>"username", "PWD"=>"password");
$conn = sqlsrv_connect($serverName, $connectionInfo);
// 获取表名
$sql = "SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE = 'BASE TABLE' AND TABLE_CATALOG='database_name'";
$stmt = sqlsrv_query($conn, $sql);
// 遍历表名
while ($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)) {
echo $row['TABLE_NAME'] . "<br />";
}
// 关闭连接
sqlsrv_free_stmt($stmt);
sqlsrv_close($conn);
```
以上代码仅供参考,具体的实现方式需要根据不同的环境和需求进行调整。
阅读全文