首页 > 解决方案 > C#从红移连接和SQL查询异常填充datagridview

问题描述

我有一个按钮,当按下该按钮时,应该使用来自红移连接的 SQL 查询的结果填充 datagridview,但是当它运行时,我得到了异常并且没有填充任何内容。

private void Button1_Click(object sender, EventArgs e)
{
    string connString = "Server=" + Properties.Settings.Default.awsconstring 
                      + ";Port=" + Properties.Settings.Default.awsport 
                      + "; User Id=" + Properties.Settings.Default.awsusername 
                      + ";Password=" + Properties.Settings.Default.awspassword 
                      + ";Database=" + Properties.Settings.Default.awsdb 
                      + "";
    string query = "SELECT * FROM schema.Table";
    NpgsqlConnection conn = new NpgsqlConnection(connString);
    NpgsqlCommand cmd = new NpgsqlCommand(query, conn);
    try
    {
        NpgsqlDataAdapter da = new NpgsqlDataAdapter();
        da.SelectCommand = cmd;
        DataTable dt = new DataTable();
        da.Fill(dt);
        testdgv.DataSource = dt;
        conn.Close();
    }
    catch (Exception ex)
    {
        MessageBox.Show("Connection error.", "Connection Error", MessageBoxButtons.OK, MessageBoxIcon.Warning);
    }
}

标签: c#sqlpostgresqlamazon-web-servicesamazon-redshift

解决方案


您没有打开连接。尝试:

...
NpgsqlConnection conn = new NpgsqlConnection(connString);
conn.Open();
...

推荐阅读