I need to get the column names after the query in order to display them in the dataGridView1 component.

To obtain and fill in the table column names I use:

 dataGridView1.Rows.Clear(); dataGridView1.Columns.Clear(); object a = comboBox1.SelectedItem; sql = "SELECT column_name FROM information_schema.columns WHERE table_name = '" + a + "'"; NpgsqlCommand com = new NpgsqlCommand(sql, con); con.Open(); NpgsqlDataReader reader; reader = com.ExecuteReader(); ArrayList nameColumns = new ArrayList(); while (reader.Read()) { try { nameColumns.Add(reader.GetValue(0)); } catch { } } dataGridView1.ColumnCount = nameColumns.Count; for (int i = 0; i < nameColumns.Count; i++) { dataGridView1.Columns[i].HeaderText = nameColumns[i].ToString(); } con.Close(); 

But how to get the name of the columns with the result of the query, given that the query for multiple tables?

1 answer 1

The column name can be obtained using the GetName method.

Direct data transfer to a sql query by gluing strings is fraught with sql injections. In addition, requests with parameters are usually more efficient, since the request plan is cached. Here you can also see: Changing values ​​in the database

  static void Npgsql(String connection) { dataGridView1.Rows.Clear(); dataGridView1.Columns.Clear(); Object a = comboBox1.SelectedItem; using (NpgsqlConnection con = new NpgsqlConnection(connection)) { String sql = "SELECT column_name FROM information_schema.columns WHERE table_name = :a"; NpgsqlCommand com = new NpgsqlCommand(sql, con); com.Parameters.AddWithValue(":a", a); con.Open(); NpgsqlDataReader reader = com.ExecuteReader(); ArrayList nameColumns = new ArrayList(); while (reader.Read()) { for (Int32 i = 0; i < reader.FieldCount; i++) { try { nameColumns.Add(reader.GetName(i)); } catch { } } } dataGridView1.ColumnCount = nameColumns.Count; for (Int32 i = 0; i < nameColumns.Count; i++) { dataGridView1.Columns[i].HeaderText = nameColumns[i].ToString(); } } } 
  • Clear, but you can at least a short example for the query SELECT idgame FROM games EXCEPT SELECT idgame FROM gamelibrary That I would understand how to read the name of the columns from the query. - CooLe
  • Names are read from the result set, that is, SELECT idgame FROM - Yaroslav