我在这里需要C#的帮助...
我正在尝试学习如何将表格与从PostgreSQL数据库获取的数据一起使用。
这就是为什么我的目标是从表中获取一些数据并将其插入到ListView中。
我的问题是:一旦启动包含ListView的窗体,我就会得到一个异常,恰好是System.InvalidOperationException. The connection is not Open
。
我不知道为什么,
下面是一些代码:
private void FormLoad(object sender, EventArgs e) {
list.View = View.Details;
list.GridLines = true;
list.FullRowSelect = true;
string connection = "Server=localhost;User Id=artemius;Password=prophet;" +
"Database=Exams;";
lista.Columns.Add("Course", 100);
lista.Columns.Add("CFU", 70);
lista.Columns.Add("Difficulty", 70);
ListViewItem item;
NpgsqlConnection conn;
try {
conn = new NpgsqlConnection(connection);
conn.Open(); //Isn't it opened here?
string sql = "select coursename, cfu, difficulty from courses where passed = false;";
string[] courses= new string[3];
NpgsqlCommand command = new NpgsqlCommand(sql);
/*--On Row Below I get System.InvalidOperationException--*/
NpgsqlDataReader dr = command.ExecuteReader();
while (dr.Read()) {
courses[0] = dr[0].ToString();
courses[1] = dr[1].ToString();
courses[2] = dr[2].ToString();
item = new ListViewItem(corso);
lista.Items.Add(item);
}
conn.Close();
}
catch(NpgsqlException ecc) {
Console.WriteLine(ecc.BaseMessage);
}
}
你们是否有解决问题的想法? 谢谢
答案 0 :(得分:1)
您尚未关联connection
和command
替换
NpgsqlCommand command = new NpgsqlCommand(sql);
作者
NpgsqlCommand command = new NpgsqlCommand(sql,conn);