SQL经验分享(二)取得数据库中所有的表名、字段名以及字段属于哪个表

2.1取得数据库中所有表名

样例数据:



 

语句:

select t.name '表名' from sysobjects t where OBJECTPROPERTY(t.id, N'IsUserTable') = 1

或者用select name from sysobjects where type='U'

执行结果:



 

 

2.2 取得所有表中的所有字段名

语句:

select distinct c.name '字段名'  from sysobjects t, syscolumns c

where t.id = c.id   and  OBJECTPROPERTY(t.id, N'IsUserTable') = 1

执行结果:



 

注:字段较多,后面略

 

2.3查所有表和字段

语句:select t.name '表名' ,c.name '字段名'  from sysobjects t, syscolumns c

where t.id = c.id   and  OBJECTPROPERTY(t.id, N'IsUserTable') = 1  group by t.name,c.name

执行结果:



 

注:字段较多,后面略

 

2.4查某个表的所有字段

Table_1原始数据:



 

语句:

select t.name,c.name '字段名'  from sysobjects t, syscolumns c

where t.id = c.id   and  OBJECTPROPERTY(t.id, N'IsUserTable') = 1

and  t.name='Table_1'

执行结果:

 



 

 

2.5查字段属于哪个表(即找含有相同字段的表)

查询姓名列在哪些表中有

语句:

select distinct t.name from sysobjects t, syscolumns c

where t.id = c.id   and  OBJECTPROPERTY(t.id, N'IsUserTable') = 1

and c.name in ('姓名')

执行结果:



 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
你可以使用Java的JDBC API来获取数据库名和字段名。以下是获取名和字段名的示例代码: ```java import java.sql.*; public class TableAndColumnNames { public static void main(String[] args) throws SQLException { // Replace the values below with your own database details String url = "jdbc:mysql://localhost:3306/mydatabase"; String username = "myusername"; String password = "mypassword"; // Connect to the database Connection connection = DriverManager.getConnection(url, username, password); // Get the metadata of the database DatabaseMetaData metaData = connection.getMetaData(); // Get the table names String[] tableTypes = {"TABLE"}; ResultSet tables = metaData.getTables(null, null, "%", tableTypes); System.out.println("Table names:"); while (tables.next()) { String tableName = tables.getString("TABLE_NAME"); System.out.println(tableName); // Get the column names for each table ResultSet columns = metaData.getColumns(null, null, tableName, "%"); System.out.println("Column names:"); while (columns.next()) { String columnName = columns.getString("COLUMN_NAME"); System.out.println(columnName); } System.out.println(); } // Close the database connection connection.close(); } } ``` 在上面的示例代码,我们首先连接到数据库,然后获取数据库的元数据。我们然后使用`getTables()`方法获取所有的名称,并使用`getColumns()`方法获取每个的所有列名称。注意,`getTables()`和`getColumns()`方法都需要指定名的模式,我们在这里使用`%`来示匹配所有名和列名。最后,我们关闭数据库连接。 请注意,这只是一个示例代码,你需要将其修改为适合自己的数据库类型和结构的代码。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值