For a reason I can’t use my MySQL-DB, so I switched to a Access DB.
I wanted to have some small functions that just do simple Queries like SELECT, UPDATE and INSERT.
I followed this small code:
using System.Data.OleDb;
using System.Windows.Forms;
using System.Data;
class Csharp_Access
{
public void Csharp_Access_Datenbank()
{
OleDbConnection con = new OleDbConnection(
@"Provider=Microsoft.Jet.OLEDB.4.0;
Data Source=C:\data.mdb");
con.Open();
string strSQL = "SELECT * FROM Tabelle1";
OleDbCommand cmd = new OleDbCommand(strSQL, con);
OleDbDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
MessageBox.Show(dr[0].ToString());
}
dr.Close();
con.Close();
}
}
When I just Copy&Paste it, this code works perfectly.
So I decided to but that code into a “dbFunctions.cs”:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.OleDb;
using System.Xml.Serialization;
namespace AquadoServerTool
{
class dbFunctions
{
/// <summary>
/// Funktion, um eine Abfrage auszuführen
/// </summary>
/// <param name="QueryStr">SQL-String</param>
/// <returns></returns>
public static OleDbDataReader QueryString(string QueryStr)
{
// string strAccessSelect = "SELECT * FROM seriennummer";
// Verbindung zur Datenbank aufbauen
OleDbConnection con = null;
try
{
con = new OleDbConnection(GlobalVar.strAccessConn);
con.Open();
}
catch (Exception)
{
return null;
}
OleDbCommand cmd = new OleDbCommand(QueryStr, con);
OleDbDataReader dr = cmd.ExecuteReader();
// while (dr.Read())
// {
// MessageBox.Show(dr[0].ToString());
// }
con.Close();
return dr;
}
}
}
For testing, I made a little button if that works:
private void button1_Click(object sender, EventArgs e)
{
OleDbDataReader dr = dbFunctions.QueryString("SELECT * FROM seriennummer;");
while (dr.Read())
{
MessageBox.Show(dr[1].ToString());
}
dr.Close();
}
Yeah, now click that button to oblivion!
But I get the error, that Read() won’t work, because it has been already closed.
Is my code simply wrong or did I just forgot something?
Greetings,
Trollwut
Your problem is that you first close the connection, and then try to read from the
DataReader. You have to keep the connection open to read.You could create a wrapper around the
DataReaderthat implementsIDisposableand closes the connection for you.Simple example:
Usage:
Another way is to simple return the data via a
DataTable.