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)); }
source share