Gathering data from Access database - c#

I want to gather some data from some tables of an Access Database, I've found some solutions online, but I haven't found ways to fill a datatable, or dataset, and get each single field properly.
Is it easier for me to get whole tables then get just the info that i want, or should I make a lot of searches in the access DB getting just what i Want each time? Any code snippets for it?
info:
The Access Database is in an ACCDB
file, with no user or password
I'm currently using VB.NET, but it
doesn't matter if you answer in C#
--[EDIT]--
Sub question:
Connecting to ACCDB format MS-ACCESS database through OLEDB

From here, you use the OleDbDataReader:
using System;
using System.Data;
using System.Data.Common;
using System.Data.OleDb;
class MainClass
{
static void Main(string[] args)
{
string connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;data source=C:\\Northwind.mdb";
OleDbConnection conn = new OleDbConnection(connectionString);
string sql = "SELECT * FROM Orders";
OleDbCommand cmd = new OleDbCommand(sql, conn);
conn.Open();
OleDbDataReader reader;
reader = cmd.ExecuteReader();
while (reader.Read())
{
Console.Write(reader.GetString(0).ToString() + " ," );
Console.Write(reader.GetString(1).ToString() + " ," );
Console.WriteLine("");
}
reader.Close();
conn.Close();
}
}

If you can fill a DataSet, you have all data (fields) in memory.
In your Project, use the Data menu to add a DataSource.
Follow the Wizard. It will create a Typed DataSet for you.
Drag the new DataSource to a Form. That will show you the code to fill the DS.

I wrote this test program to retrieve data from a DAO database. This should work for you too.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.OleDb;
namespace TestReadCfg
{
class Program
{
static void Main(string[] args)
{
string connectionString =
"Provider=Microsoft.Jet.OLEDB.4.0;Data Source="
+ "c:\\Avtron\\addapt\\Configuration\\testDao.db;Jet OLEDB:Database Password=RainbowTrout;";
string queryString = "SELECT * from Sections order by Address";
using (OleDbConnection connection = new OleDbConnection(connectionString))
{
// Create the Command and Parameter objects.
OleDbCommand command = new OleDbCommand(queryString, connection);
try
{
connection.Open();
OleDbDataReader reader = command.ExecuteReader();
int iRecNbr = 1;
while (reader.Read())
{
String sRecord = string.Empty;
sRecord = string.Format("Record {0}: ", iRecNbr);
for (int i = 0; i < reader.FieldCount; i++)
{
sRecord += string.Format("{0} ", reader[i].ToString());
}
Console.WriteLine(sRecord);
iRecNbr++;
}
reader.Close();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
Console.ReadLine();
}
}
}

Related

Load data from SQL Server database to C#

I get this error:
System.Data.SqlClient.SqlException: 'Incorrect syntax near the keyword 'Table'.
when I run the program; it said the error near to table!
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace WindowsFormsApp3
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
string SOURCE = #"Data Source=DESKTOP-K39PU4T\SQLEXPRESS;Initial Catalog=Mohamed;Integrated Security=True";
SqlConnection CON = new SqlConnection(SOURCE);
CON.Open();
MessageBox.Show("DB Connected");
string SqlSelectQuery = " Select*From Table Where ID ="+ int.Parse(textBox1.Text);
SqlCommand cmd = new SqlCommand(SqlSelectQuery, CON);
SqlDataReader dr = cmd.ExecuteReader();
if (dr.Read())
{
textBox2.Text = (dr["Name"].ToString());
textBox3.Text = (dr["Surname"].ToString());
textBox4.Text = (dr["Lastname"].ToString());
}
else
{
textBox1.Text = "";
textBox2.Text = "";
textBox3.Text = "";
textBox4.Text = "";
MessageBox.Show("No Record Found Please Enter Correct Id");
}
CON.Close();
}
}
}
I want to load the data from SQL Server to ASP.NET in Visual Studio
Table is key word, if you have table named "Table" you may need to use [Table] for escape keyword in the SQL string, otherwise give the correct table name instead of Table. also you better use parameters instead of concatenating string as sql statement.
string SqlSelectQuery = "Select * From [Table] Where ID =#ID";
SqlCommand cmd = new SqlCommand(SqlSelectQuery, CON);
cmd.Parameters.AddWithValue("#ID", int.Parse(textBox1.Text));
What is the table name from which you want to get data?
if its name is Table then replace " Select*From Table Where ID =" with " Select * From \"Table\" Where ID ="
otherwise replace Table with actual table name

The name "ABC..." does not exist in the current context. c# SQL Console program

I'm new at this. Im making a c# console program that reads sql database via datareader, displays a statement if any row matches the query and updates those rows via sql update query. But I can't figure out how to fix this error. here is my code. help appreciated. thanks.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Data.SqlClient;
namespace emailsend
{
class Program
{
#region Connection String
static private SqlConnection connection = new SqlConnection("Data Source=server;Initial Catalog=dbTrainning;User ID=user;Password=123");
#endregion
static void Main(string[] args)
{
#region SQL Select Unsent Query
string Sql = "SELECT * FROM People where Visits is Null;";
SqlCommand cmd = new SqlCommand(Sql, connection);
#endregion
#region Open DB Connection
if (connection.State != ConnectionState.Open)
{
connection.Open();
}
#endregion
SqlDataReader DR = cmd.ExecuteReader();
#region Try Catch Block
try
{
while (DR.Read())
{
#region Fetching DB data
DateTime TimeStamp = (DateTime)DR["ExceptionDate"];
string VNumber = (string)DR["VisitNumber"];
Console.Write("Total Visits = " +VNumber "\n");
#endregion
DR.Close();
}
cmd = new SqlCommand("UPDATE People SET Visits = '0' WHERE VisitNumber = '" + VNumber + "'", connection); //The name 'VNumber' does not exist in the current context
cmd.ExecuteNonQuery();
}
catch (SqlException exception)
{
Console.Write(exception);
}
finally
{
connection.Close();
}
#endregion
}
}
}
It is because you create VNumber in a while loop and it is not visible outside. try it:
try
{
string VNumber = null; //outside the loop
while (DR.Read())
{
#region Fetching DB data
DateTime TimeStamp = (DateTime)DR["ExceptionDate"];
VNumber = (string)DR["VisitNumber"];
Console.Write("Total Visits = " +VNumber "\n");
#endregion
DR.Close();
}
cmd = new SqlCommand("UPDATE People SET Visits = '0' WHERE VisitNumber = '" + VNumber + "'", connection); //The name 'VNumber' does not exist in the current context
cmd.ExecuteNonQuery();
}

Connection to database

I am trying to create a class that I can use within my application to easily connect to my database and run queries as needed. I found this post but it is not quite working like I expect.
Here is my class:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.SqlClient;
//a class that returns a connection to the database
namespace epaCUBE_Utility_Tool
{
public class epaCUBE_DB
{
public static SqlConnection GetConnection()
{
string str = "user id=MyUserName;" +
"password=MyPassword;server=myServer;" +
"database=myDatabase; " +
"connection timeout=30";
SqlConnection con = new SqlConnection(str);
con.Open();
return con;
}
}
}
and here is how I am trying to use it:
private void button1_Click(object sender, EventArgs e)
{
var connection = epaCUBE_DB.GetConnection();
connection.Open();
SqlDataReader rdr = null;
string CommandText = "SELECT Field1, Field2 FROM TableName";
SqlCommand cmd = new SqlCommand(CommandText, connection);
rdr = cmd.ExecuteReader();
while (rdr.Read())
{
this.comboBox1.Items.Add(rdr["Field1"].ToString() +
": " + rdr["Field2"].ToString());
}
connection.Close();
}
when I press the button I get an error
InvalidOperationException: The connection was not closed. The connection's current state is open.
What am I doing wrong?
Thanks,
Leslie
GetConnection calls Open for you, but you're calling it again manually after you called GetConnection. Call it inside GetConnection or outside, but not both places.
Problem is in GetConnection() you already open the connection. All these problems came with your static method.
This is not good way to do this, better to create a new instance of SqlConnection when you need and dispose after use. The underlying connection pooling will be able to manage the physical connections.
separate your UI with Data access, Here you read the data from database and same time adding items to controls. You need to re-factor the code.
You can have method like below to retrieve data
public List<string> GetFields()
{
List<string> fields = new List<string>();
string CommandText = "SELECT Field1, Field2 FROM TableName";
using (var connection = new SqlConnection(epaCUBE_DB.GetConnectionString()))
{
connection.Open();
using (var cmd = new SqlCommand(CommandText, connection))
using (var reader = cmd.ExecuteReader())
{
while (reader.Read())
{
fields.Add(reader["Field1"].ToString() + ": " + reader["Field2"].ToString());
}
}
}
return fields;
}
You're trying to open a connection which is already open, this results in exception.
before opening the connection check the connection status and then open the connection
cmd.Connection.Open();
add the following check/cleanup code:
if (cmd.Connection.State == ConnectionState.Open)
{
cmd.Connection.Close();
}
I program quite defensively; I expect faults to occur and try to handle that gracefully.
As such..
// Define this once in a class and re-use for every connection..
string myConnString = "user id=MyUserName;" +
"password=MyPassword;server=myServer;" +
"database=myDatabase; " +
"connection timeout=30";
using (SqlConnection mySqlConnection = new SqlConnection(myConnString))
{
using (SqlCommand mySQLCommand = new SqlCommand("SELECT Field1, Field2 FROM TableName", mySqlConnection) { CommandType = CommandType.Text})
{
try
{
mySqlConnection.Open();
using (SqlDataReader rdr = mySQLCommand.ExecuteReader())
{
this.comboBox1.Items.Add(rdr["Field1"].ToString() + ": " + rdr["Field2"].ToString());
}
}
catch (Excecption e)
{
// Deal with it as you wish
}
mySqlConnection.Close();
}
}

reading one record from access in C#

My requirement is to read Date column from access file and use one value to append it to a file name, so as to create file with date timestamp using the db value.
I am trying following approach but it gives me exception "No data exists for the row/column":
here's the code
OleDbConnection conn = new OleDbConnection(connectionString);
OleDbConnection conn1 = new OleDbConnection(connectionString);
string dt = "SELECT top 1 Date FROM Events";
OleDbCommand cmd1 = new OleDbCommand(dt, conn1);
conn1.Open();
OleDbDataReader rdr = cmd1.ExecuteReader();
string time_stmp = rdr.GetInt32(0).ToString();
rdr.Close();
conn1.Close();
string path = text_dir + "\\" + time_stmp + "_" + "BWC_Ejournal.txt";
You'll need to call the Read() method on the OleDbDataReader object before accessing its data.
E.g.
OleDbDataReader rdr = cmd1.ExecuteReader();
string time_stmp = "";
if(rdr.Read())
{
time_stmp = rdr.GetInt32(0).ToString();
}
else
{
//handle no data situation here
}
This will also allow to handle a situation where no data is returned more gracefully too.
DATE is a reserved word in ACE/Jet SQL. Try this instead:
string dt = "SELECT TOP 1 [Date] FROM Events";
Edit
On taking a closer look at your code I notice that you create the OleDbCommand object before the connection is opened. I've seen that cause problems as well. FWIW, the following code works for me:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.OleDb;
namespace oleDbTest
{
class Program
{
static void Main(string[] args)
{
using (var con = new OleDbConnection(
"Provider=Microsoft.ACE.OLEDB.12.0;" +
#"Data Source=C:\__tmp\main.accdb;"))
{
con.Open();
using (var cmd = new OleDbCommand(
"SELECT TOP 1 [Date] FROM [Events]", con))
{
string time_stmp = Convert.ToDateTime(cmd.ExecuteScalar()).ToString("yyyyMMdd");
Console.WriteLine(time_stmp.ToString());
}
con.Close();
}
Console.WriteLine("Done.");
System.Threading.Thread.Sleep(2000);
}
}
}

Microsoft jet database engine can't find table

I corrected the spelling mbd to mdb but now the error is
Micorsoft Jet database engine cannot find the input table or query employee make sure it exist and that its name is spelled correctly.
What I want to do is connect to database and extract four fields in the texbox here is my code
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.OleDb;
namespace Empdetails
{
public partial class EGUI : Form
{
private OleDbConnection dbConn; // Connectionn object
private OleDbCommand dbCmd; // Command object
private OleDbDataReader dbReader;// Data Reader object
private Emp1 Edetails;
private string sConnection;
private string sql;
public EGUI()
{
InitializeComponent();
}
private void button1_Click(object sender,System.EventArgs e)
{
try
{
// Construct an object of the OleDbConnection
// class to store the connection string
// representing the type of data provider
// (database) and the source (actual db)
sConnection =
"Provider=Microsoft.Jet.OLEDB.4.0;" +
"Data Source=employee.mdb";
dbConn = new OleDbConnection(sConnection);
dbConn.Open();
// Construct an object of the OleDbCommand
// class to hold the SQL query. Tie the
// OleDbCommand object to the OleDbConnection
// object
sql = "Select * From employee";
dbCmd = new OleDbCommand();
dbCmd.CommandText = sql;
dbCmd.Connection = dbConn;
// Create a dbReader object
dbReader = dbCmd.ExecuteReader();
while (dbReader.Read())
{
Edetails = new Emp1
(dbReader["Name"].ToString(), dbReader["Address"].ToString(), dbReader["SocialSecurityNumber"].ToString(), dbReader["Rate"].ToString());
textBox1.Text = dbReader["Name"].ToString();
textBox2.Text = dbReader["Address"].ToString();
textBox3.Text = dbReader["SocialSecurityNumber"].ToString();
textBox4.Text = dbReader["Rate"].ToString();
// tb1.Text = dbReader["FirstName"].ToString();
} // tb2.Text = dbReader["LastName"].ToString();
dbReader.Close();
dbConn.Close();
}
catch (System.Exception ex)
{
MessageBox.Show("exeption" + ex.ToString());
}
}
private void EGUI_Load(object sender, EventArgs e)
{
}
}
Tim and binil are right, you need to provide the full path. I tested your code and it works when you add the full path
try
{
// Construct an object of the OleDbConnection
// class to store the connection string
// representing the type of data provider
// (database) and the source (actual db)
string sConnection =
"Provider=Microsoft.Jet.OLEDB.4.0;" +
"Data Source=C:\\Code\\StackOverflowSamples\\ReadFromAccessDB\\employee.mdb";
using (OleDbConnection dbConn = new OleDbConnection(sConnection))
{
dbConn.Open();
// Construct an object of the OleDbCommand
// class to hold the SQL query. Tie the
// OleDbCommand object to the OleDbConnection
// object
string sql = "Select * From employee";
OleDbCommand dbCmd = new OleDbCommand();
dbCmd.CommandText = sql;
dbCmd.Connection = dbConn;
// Create a dbReader object
using (OleDbDataReader dbReader = dbCmd.ExecuteReader())
{
while (dbReader.Read())
{
Console.WriteLine(dbReader["EmployeeName"].ToString());
Console.WriteLine(dbReader["Address"].ToString());
Console.WriteLine(dbReader["SSN"].ToString());
Console.WriteLine(dbReader["Rate"].ToString());
}
}
}
}
catch (System.Exception ex)
{
Console.WriteLine("exeption" + ex.ToString());
}
Console.ReadLine();
}
Do you need to provide the full path to the file in the connect string?

Categories