Get Database data using c#

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • ghjk
    Contributor
    • Jan 2008
    • 250

    Get Database data using c#

    I'm new to c# and didn't write any c# code yet. I'm using postgres database. I want to connect to postgres and retriew some data to test my database connectivity. This is my code.

    Code:
    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Text;
    using System.Windows.Forms;
    using Npgsql;
    
    namespace PostgreSQLTEst
    {
        public partial class Form1 : Form
        {
           		
            public Form1()
            {
                InitializeComponent();
            }
    
            private void Form1_Load(object sender, EventArgs e)
            {
                try
                {
                    // PostgeSQL-style connection string
                    string connstring = String.Format("Server=xxx;Port=xxx;User Id=xxx;Password=xxx;Database=xxx;");
                  
                    // Making connection with Npgsql provider
                    NpgsqlConnection conn = new NpgsqlConnection(connstring);
                    conn.Open();
                   
                    string sql = "SELECT * FROM simple_table";
                   conn.Close();
                }
                catch (Exception msg)
                {
                
                    MessageBox.Show(msg.ToString());
                    //throw;
                }
    
            }
        }
    }
  • tlhintoq
    Recognized Expert Specialist
    • Mar 2008
    • 3532

    #2
    You have described no problem, error, exception or issue.
    You have asked no question. What is it you need of the volunteers here?

    Database How two parts 1 and 2

    Comment

    • cloud255
      Recognized Expert Contributor
      • Jun 2008
      • 427

      #3
      You create a connection, you open it, create the query you want to use and then close the connection. You are missing only one step:
      You need to create a NpgsqlCommand and assign your query to the CommandText member, then call the command with the ExecuteReader method.

      Comment

      Working...