By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
459,296 Members | 1,457 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 459,296 IT Pros & Developers. It's quick & easy.

Get Database data using c#

100+
P: 250
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.

Expand|Select|Wrap|Line Numbers
  1. using System;
  2. using System.Collections.Generic;
  3. using System.ComponentModel;
  4. using System.Data;
  5. using System.Drawing;
  6. using System.Text;
  7. using System.Windows.Forms;
  8. using Npgsql;
  9.  
  10. namespace PostgreSQLTEst
  11. {
  12.     public partial class Form1 : Form
  13.     {
  14.  
  15.         public Form1()
  16.         {
  17.             InitializeComponent();
  18.         }
  19.  
  20.         private void Form1_Load(object sender, EventArgs e)
  21.         {
  22.             try
  23.             {
  24.                 // PostgeSQL-style connection string
  25.                 string connstring = String.Format("Server=xxx;Port=xxx;User Id=xxx;Password=xxx;Database=xxx;");
  26.  
  27.                 // Making connection with Npgsql provider
  28.                 NpgsqlConnection conn = new NpgsqlConnection(connstring);
  29.                 conn.Open();
  30.  
  31.                 string sql = "SELECT * FROM simple_table";
  32.                conn.Close();
  33.             }
  34.             catch (Exception msg)
  35.             {
  36.  
  37.                 MessageBox.Show(msg.ToString());
  38.                 //throw;
  39.             }
  40.  
  41.         }
  42.     }
  43. }
  44.  
Dec 8 '09 #1
Share this Question
Share on Google+
2 Replies


tlhintoq
Expert 2.5K+
P: 3,525
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
http://bytes.com/topic/net/insights/...e-your-program
http://bytes.com/topic/net/insights/...rogram-part-ii
Dec 8 '09 #2

Expert 100+
P: 427
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.
Dec 8 '09 #3

Post your reply

Sign in to post your reply or Sign up for a free account.