【问题标题】:Reading database names off a Server with C#使用 C# 从服务器读取数据库名称
【发布时间】:2015-03-18 15:02:35
【问题描述】:

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

这是我目前为止的工作;

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

【问题讨论】:

    标签: c# mysql database


    【解决方案1】:

    请注意,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        
    }
    

    【讨论】:

    • .DataBind();不适合我。出现一个错误,提示没有“DataBind 的定义”。
    • 删除那行代码。我假设它是 ASP.Net。如果是 WinForms 那么 DataGridView 没有 DataBind() 方法。
    • 好的,我已经删除了。但是,dataGrid 上仍然没有显示任何内容。如何让它显示服务器中数据库的名称?
    猜你喜欢
    • 1970-01-01
    • 2012-05-15
    • 1970-01-01
    • 2016-03-10
    • 1970-01-01
    • 2017-09-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多