Display database information in ado.net

How can I view all databases in a curent connection using ado.net? Then view all the tables in each database.

+4
source share
3 answers

he gets the whole database

it gets all the tables from the database (now this link has been deleted, but change the code a bit)

ADO.Net: get table definition from SQL server tables

you can iterate over the database and get all the tables

+5
source

To list all databases, you need to specify a connection string without an initial database. Then you can execute the sp_databases stored procedure.

To list all the tables in the database, you need to query INFORMATION_SCHEMA.Tables .

SAMPLES

To get the databases:

System.Data.SqlClient.SqlConnection SqlCon = new System.Data.SqlClient.SqlConnection("server=192.168.0.1;uid=sa;pwd=1234"); SqlCon.Open(); System.Data.SqlClient.SqlCommand SqlCom = new System.Data.SqlClient.SqlCommand(); SqlCom.Connection = SqlCon; SqlCom.CommandType = CommandType.StoredProcedure; SqlCom.CommandText = "sp_databases"; System.Data.SqlClient.SqlDataReader SqlDR; SqlDR = SqlCom.ExecuteReader(); while(SqlDR.Read()) { Console.WriteLine(SqlDR.GetString(0)); } 

To get tables:

 string connectionString = "..."; DataTable tables = new DataTable("Tables"); using (SqlConnection connection = new SqlConnection(connectionString)) { SqlCommand command = connection.CreateCommand(); command.CommandText = "select table_name as Name from INFORMATION_SCHEMA.Tables where TABLE_TYPE = 'BASE TABLE'"; connection.Open(); tables.Load(command.ExecuteReader( CommandBehavior.CloseConnection)); } 
+5
source

In Visual Studio 2010

Select View => Server Explorer

Then write down the server name, if you use SQL Server authentication, select it, write your username and password, select or enter the database name => OK

In the server explorer under Data Connections you will see your database and tables.

0
source

Source: https://habr.com/ru/post/1347894/


All Articles