簡體   English   中英

使用C#從服務器讀取數據庫名稱

[英]Reading database names off a Server with C#

基本上,我要創建的是一個程序,該程序允許用戶從服務器讀取多個數據庫名稱。 我已將服務器連接到該程序,並且連接正常(為安全起見,某些詳細信息已替換為*)。 但是,我似乎無法使數據庫名稱出現在數據網格視圖中。 救命?!

到目前為止,這是我的工作;

private void connectDB_Click(object sender, EventArgs e)
    {
        try
        {
            using (SqlConnection connection = new SqlConnection(@"Data Source=***;Integrated Security=False;User ID=***;Password=***;Connect Timeout=15;Encrypt=False;TrustServerCertificate=False"))
            using (SqlCommand command = new SqlCommand("Select * FROM sys.databases;"))
            {
                connection.Open();
                using (SqlDataReader reader = command.ExecuteReader())
                {
                    while (reader.Read())
                    {
                        foreach(SqlDataReader read in reader)
                        {
                        int n = dataGridDataBase.Rows.Add();
                        dataGridDataBase.Rows[n].Cells[0].Value = reader;
                        }
                    }

                }
            }

        }
        catch (Exception ex)
        {
            throw ex;
        }
    }

請注意,SQLCommand對象未與SQLConnection鏈接。

using (SqlConnection connection = new SqlConnection(@"Data Source=***;Integrated Security=False;User ID=***;Password=***;Connect Timeout=15;Encrypt=False;TrustServerCertificate=False"))
using (SqlCommand command = new SqlCommand("Select * FROM sys.databases;"))
{
      command.Connection = connection;//This is missing in your code.
      connection.Open();

      //Bind your datagridview to rows from the reader        
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM