NpgsqlConnection conn = new NpgsqlConnection("Server=127.0.0.1;Port=5432;User Id=postgres;Password=t@ida1234;Database=Demo;"); conn.Open(); NpgsqlCommand command = new NpgsqlCommand("select * from shop_sale", conn); try { NpgsqlDataReader reader = command.ExecuteReader(); while (reader.Read()) { string shop = reader["shop"].ToString(); ; string no = reader["no"].ToString(); ; Console.WriteLine(shop + "\t" + no); } } finally { conn.Close(); }
如果要放進DataGridView中,我們必須先拉一個DataGridView出來,命名為dataGridView1
宣告一個用來存放資料的DataTable
DataTable dt = new DataTable();用NpgsqlDataReader裡的資料填進DataTable
dt.Load(reader);指定DataGridView 的資料來源
dataGridView1.DataSource = dt;
完整程式碼
using System; using System.ComponentModel; using System.Data; using System.Windows.Forms; using Npgsql; public partial class Form1 : Form { public Form1() { InitializeComponent(); getData(); } private void getData() { DataTable dt = new DataTable(); NpgsqlConnection conn = new NpgsqlConnection("Server=127.0.0.1;Port=5432;" + "User Id=postgres;Password=t@ida1234;" + "Database=Demo;"); conn.Open(); NpgsqlCommand command = new NpgsqlCommand("select * from shop_sale", conn); try { NpgsqlDataReader reader = command.ExecuteReader(); dt.Load(reader); dataGridView1.DataSource = dt; } finally { conn.Close(); } } }執行結果
沒有留言:
張貼留言