Microsoft jet database engine can't find table - c#

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?

Related

Import Excel to Access with c#

I've imported an Excel file and displayed the data using a datagrid view, but I want also to save in to my MS Access database.
Can it be done with OleDbCommand and select * into ?
Below is the code for my import from an Excel file; for the import I created it based on another post here:
private void BtnImport1_Click(object sender, EventArgs e)
{
try
{
OpenFileDialog openfile1 = new OpenFileDialog();
openfile1.Filter = "Excel Files | *.xlsx; *.xls; *.xlsm";
openfile1.Title = "Seleccione el archivo de Excel";
if (openfile1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
if (openfile1.FileName.Equals("") == false)
{
this.tBox1.Text = openfile1.FileName;
Ruta = openfile1.FileName;
}
}
string constr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + Ruta + ";Extended Properties = \"Excel 12.0; HDR=YES;\" ; ";
OleDbConnection con = new OleDbConnection(constr);
OleDbDataAdapter MyDataAdapter = new OleDbDataAdapter("Select * From [Hoja 1$]", con);
DataTable dt1Excel = new DataTable();
MyDataAdapter.Fill(dt1Excel);
dataGridView1.DataSource = dt1Excel;
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
Try it like this and feedback.
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 WindowsFormsApplication2
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
//here is a sample code which reads an Excel file Sheet1 which has 2 columns
//And inserts the same into an access table
//Change the file names, sheet name, table names and column names as per your requirements
//File Names, replae with your file names
string fileNameExcel = #"C:\your_path_here\Book1.xls";
string fileNameAccess = #"C:\your_path_here\Database1.mdb";
//Connection string for Excel
string connectionStringExcel =
string.Format("Data Source= {0};Provider=Microsoft.Jet.OLEDB.4.0;Extended Properties=Excel 8.0;", fileNameExcel);
//Connection string for Access
string ConnectionStringAccess =
string.Format("Data Source= {0}; Provider=Microsoft.Jet.OLEDB.4.0; Persist security Info = false", fileNameAccess);
//Connection object for Excel
OleDbConnection connExcel = new OleDbConnection(connectionStringExcel);
//Connection object for Access
OleDbConnection connAccess = new OleDbConnection(ConnectionStringAccess);
//Command object for Excel
OleDbCommand cmdExcel = connExcel.CreateCommand();
cmdExcel.CommandType = CommandType.Text;
cmdExcel.CommandText = "SELECT * FROM [Sheet1$]";
//Command object for Access
OleDbCommand cmdAccess = connAccess.CreateCommand();
cmdAccess.CommandType = CommandType.Text;
cmdAccess.CommandText = "INSERT INTO Table1 (Column1, Column2) VALUES(#column1, #column2)";
//Add parameter to Access command object
OleDbParameter param1 = new OleDbParameter("#column1", OleDbType.VarChar);
cmdAccess.Parameters.Add(param1);
OleDbParameter param2 = new OleDbParameter("#column2", OleDbType.VarChar);
cmdAccess.Parameters.Add(param2);
//Open connections
connExcel.Open();
connAccess.Open();
//Read Excel
OleDbDataReader drExcel = cmdExcel.ExecuteReader();
while (drExcel.Read())
{
//Assign values to access command parameters
param1.Value = drExcel[0].ToString();
param2.Value = drExcel[1].ToString();
//Insert values in access
cmdAccess.ExecuteNonQuery();
}
//close connections
connAccess.Close();
connExcel.Close();
}
}
}

How do i add textbox values to Access database?

I want to add textbox values to relevant columns in access database, the connection has been established but when i click the submit button the values are not added.
here is the code i tried, any help is appreciated
protected void Button1_Click(object sender, EventArgs e)
{
string EmailAddress = TextBox1.Text;
string UserName = TextBox2.Text;
string Password = TextBox3.Text;
try
{
OleDbConnection con = new OleDbConnection(#"Provider = Microsoft.ACE.OLEDB.12.0; Data Source = C:\Users\Bheki Ndhlovu\source\WebSites\WebSite8\App_Data\UserDatabase.accdb; Persist Security Info = False;");
OleDbCommand cmd = new OleDbCommand();
cmd = new OleDbCommand("INSERT INTO User(EmailAddress, UserName, Password) VALUES(#EmailAddress, #UserName, #Password)");
con.Open();
if (con.State == ConnectionState.Open)
{
TextBox1.Text = "sssss";
cmd.Parameters.Add("#EmailAddress", OleDbType.VarChar).Value = TextBox1.Text;
cmd.Parameters.Add("#UserName", OleDbType.VarChar).Value = TextBox2.Text;
cmd.Parameters.Add("#Password", OleDbType.VarChar).Value = TextBox3.Text;
cmd.ExecuteNonQuery();
con.Close();
}
}
catch (Exception error)
{
//Show error message as error.Message
}
}
Try adding connection string with OleDbCommand.
cmd = new OleDbCommand("INSERT INTO User(EmailAddress, UserName, Password) VALUES(#EmailAddress, #UserName, #Password)",con);
Here is an example were all data operations reside in a class. If the add new record is successful the new primary key is returned. On failure you can query the exception that raised the problem for failure.
using System;
using System.Windows.Forms;
using System.Data.OleDb;
using System.IO;
namespace MS_AccessAddNewRecord_cs
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void addRecordButton_Click(object sender, EventArgs e)
{
var ops = new Operations();
var newId = 0;
if (ops.AddNewRow(companyTextBox.Text, contactNameTextBox.Text, contactTitleTextBox.Text, ref newId))
{
newIdentifierTextBox.Text = $"{newId}";
}
else
{
MessageBox.Show($"{ops.Exception.Message}");
}
}
}
/// <summary>
/// This class should be in a separate class file, I placed it here for easy of learning
/// </summary>
public class Operations
{
private OleDbConnectionStringBuilder Builder = new OleDbConnectionStringBuilder
{
Provider = "Microsoft.ACE.OLEDB.12.0",
DataSource = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Database1.accdb")
};
private Exception mExceptiom;
public Exception Exception
{
get
{
return mExceptiom;
}
}
/// <summary>
/// Add a new record, upon success return the new primary key for the record in pIdentifier parameter
/// </summary>
/// <param name="pName"></param>
/// <param name="pContactName"></param>
/// <param name="pContactTitle"></param>
/// <param name="pIdentfier"></param>
/// <returns></returns>
public bool AddNewRow(string pName, string pContactName, string pContactTitle, ref int pIdentfier)
{
bool Success = true;
try
{
using (OleDbConnection cn = new OleDbConnection { ConnectionString = Builder.ConnectionString })
{
using (OleDbCommand cmd = new OleDbCommand { Connection = cn })
{
cmd.CommandText = "INSERT INTO Customers (CompanyName,ContactName, ContactTitle) " +
"Values(#CompanyName,#ContactName, #ContactTitle)";
cmd.Parameters.AddWithValue("#CompanyName", pName);
cmd.Parameters.AddWithValue("#ContactName", pContactName);
cmd.Parameters.AddWithValue("#ContactTitle", pContactTitle);
cn.Open();
int Affected = cmd.ExecuteNonQuery();
if (Affected == 1)
{
cmd.CommandText = "Select ##Identity";
pIdentfier = Convert.ToInt32(cmd.ExecuteScalar());
}
}
}
}
catch (Exception ex)
{
Success = false;
mExceptiom = ex;
}
return Success;
}
}
}
Perhaps in the Page_Load method you do not have a if(!isPostback) and so the value of the TextBoxes are getting reset on a postback before the Button1_Click method is executed.
If EmptyWaterHole's answer is not the problem, is it erroring out on the connection?
Be sure 'VarChar' is the correct data type for each of the fields.
Also, be sure the values do not exceed the size (ie: if you set the field to only allow up to 25 characters and your value is over 25 characters, the value will not be added).
In addition, if you are not allowing nulls and one of the values exceeds the limit, the whole record will not be added.
Mr. Hungry. Try it like this.
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 WindowsFormsApplication2
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
OleDbConnection conn;
conn = new OleDbConnection(#"Provider=Microsoft.Jet.OleDb.4.0;Data Source=C:\your_path_here\Northwind.mdb");
conn.Open();
OleDbCommand cmd = conn.CreateCommand();
cmd.CommandText = #"INSERT INTO MyExcelTable([Fname], [Lname], [Address])VALUES('" + textBox1.Text + "', '" + textBox2.Text + "','" + textBox3.Text + "')";
cmd.ExecuteNonQuery();
conn.Close();
}
public OleDbConnection myCon { get; set; }
private void button2_Click(object sender, EventArgs e)
{
OleDbConnection conn = new OleDbConnection();
conn.ConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\Ryan\Desktop\Coding\Microsoft Access\Northwind.mdb";
string fstName = textBox1.Text.Trim();
string lstName = textBox2.Text.Trim();
string adres = textBox3.Text.Trim();
OleDbCommand cmd = new OleDbCommand(#"INSERT INTO MyExcelTable (FName, LName, Address) VALUES (#FName, #LName, #Address)")
{
Connection = conn
};
conn.Open();
if (conn.State == ConnectionState.Open)
{
// you should always use parameterized queries to avoid SQL Injection
cmd.Parameters.Add("#FName", OleDbType.VarChar).Value = fstName;
cmd.Parameters.Add("#LName", OleDbType.VarChar).Value = lstName;
cmd.Parameters.Add("#Address", OleDbType.VarChar).Value = adres;
try
{
cmd.ExecuteNonQuery();
MessageBox.Show(#"Data Added");
conn.Close();
}
catch (OleDbException ex)
{
MessageBox.Show(ex.Source + "\n" + ex.Message);
conn.Close();
}
}
else
{
MessageBox.Show(#"Connection Failed");
}
}
}
}
try this it will work if you are using access as your database
try
{
OleDbCommand command = new OleDbCommand();
command.Connection = connection;
command.CommandText = "INSERT INTO REPORT (patientName,tel,hostel,id no,department,diagnose,gender) values(#patientName,#tel,#hostel,#id no,#department,#diagnose,#gender)";
connection.Open();
command.Parameters.AddWithValue("#patientName", textBox1.Text);
command.Parameters.AddWithValue("#tel", textBox2.Text);
command.Parameters.AddWithValue("#hostel", textBox3.Text);
command.Parameters.AddWithValue("#id no", textBox4.Text);
command.Parameters.AddWithValue("#department", textBox5.Text);
command.Parameters.AddWithValue("#diagnose", richTextBox1.Text);
command.Parameters.AddWithValue("#gender", textBox6.Text);
command.ExecuteNonQuery();
connection.Close();
MessageBox.Show("Patient record Have been save successfully....");
}
catch (Exception ex)
{
MessageBox.Show("error" + ex);
}

Error- Connection String property has not been initialized (C# Database)?

Error:
The error says:- The ConnectionString Property has not been
initialized at system.data.OledbOledConnection.PermissionDemand().
I am unable to figure out the error. Can someone explain what does it mean and how to solve it?
C# 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;//microsoft database
namespace AccessLoginApp
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
try
{
OleDbConnection connection = new OleDbConnection();
connection.ConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\admin\Documents\Book Database.accdb;
Persist Security Info=False;";
}
catch (Exception ex)
{
MessageBox.Show("Error"+ ex);
}
}
private void button1_Click(object sender, EventArgs e)
{
try{
OleDbConnection connection = new OleDbConnection();
connection.Open();
OleDbCommand command = new OleDbCommand();
command.Connection = connection;
command.CommandText = " Insert into Book Name(Book Name,Book Number,Publisher) values('" + bookName.Text + "','" + bookNumber.Text + "','" + publisher.Text + "')";
command.ExecuteNonQuery();
MessageBox.Show("Data Saved");
}
catch (Exception ex)
{
MessageBox.Show("Error" + ex);
}
}
}
}
The variable connection in the form load and the button1_Click event are different instance of the class OleDbConnection(obviously they are different) and you have not initialized the connection variable with connection string in the button1_Click event(It causing the error as well). If you do that means your code will works just fine, If you replace the concatenated queries with Parameterized queries means your code will works great. And the introduction of using statements will makes your code perfect. You can try the following:
string conString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\admin\Documents\Book Database.accdb;Persist Security Info=False;";
// This will be the connection string
private void Form1_Load(object sender, EventArgs e)
{
// Need not to do anything regarding connection
// some other statements if needed
}
private void button1_Click(object sender, EventArgs e)
{
try
{
using (OleDbConnection connection = new OleDbConnection(conString)) // Create and initialize connection object
{
connection.Open();
using (OleDbCommand command = new OleDbCommand())
{
command.Connection = connection;
command.CommandText = " Insert into Book(Book_Name,Book_Number,Publisher) values(#BookName,#BookNumber,#Publisher)";
command.Parameters.Add("#BookName", OleDbType.VarChar).Value = bookName.Text;
command.Parameters.Add("#BookNumber", OleDbType.Integer).Value = bookNumber.Text;
command.Parameters.Add("#Publisher", OleDbType.VarChar).Value = publisher.Text;
command.ExecuteNonQuery();
}
}
MessageBox.Show("Data Saved");
}
catch (Exception ex)
{
MessageBox.Show("Error" + ex);
}
}

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();
}
}

Gathering data from Access database

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();
}
}
}

Categories