使用C#从服务器读取数据库名称

时间:2015-03-18 15:02:36

标签: c# mysql database

基本上我正在创建的是一个允许用户从服务器读取多个数据库名称的程序。我已经将服务器连接到程序并且连接正常(为安全起见,某些细节被替换为*)。但是,我似乎无法使数据库名称出现在数据网格视图中。帮助?!

到目前为止,这是我的工作;

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;
        }
    }

1 个答案:

答案 0 :(得分:0)

请注意,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        
}
相关问题