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);
}
}
Related
Sir,
I wrote a program for update data in my MS-Access database. but It show error message box. What is my fault? How can I fix it.
I am using MS-Access 2010. Database formet (.accdb). Other Information:
Table Name: user_info.
Table's Fields are: a) Name b) Designation c) User_Name d) Password.
Visual Studio 2019
C#
My Trying Code is:
using System.Data;
using System.Windows.Forms;
using System.Data.OleDb;
namespace Shahid_Abdul_Hamid_Hall_1._1
{
public partial class ChangePassword : Form
{
OleDbConnection conn = new OleDbConnection();
public ChangePassword(String User)
{
InitializeComponent();
conn.ConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\SAHHDB1.accdb;Persist Security Info=False;";
lvl_user.Text = User;
}
private void ChangePassword_Load(object sender, EventArgs e)
{
}
private void btn_cancel_Click(object sender, EventArgs e)
{
this.Hide();
}
private void btn_change_Click(object sender, EventArgs e)
{
if (txt_new_pass.Text == txt_cnew_pass.Text)
{
try
{
conn.Open();
OleDbCommand cmd = conn.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "update user_info set Password = '"+ txt_new_pass.Text + "' where User_Name = '"+ lvl_user.Text + "'";
cmd.ExecuteNonQuery();
conn.Close();
}
catch (Exception ew)
{
MessageBox.Show("Error" + " " + ew);
}
}
else
{
MessageBox.Show("'Confirm New Password' dosen't Match 'New Password'. Try Again.");
}
}
}
}
You may be best-off trying something like LINQ Connect Express, and letting VS auto-generate the code.
Otherwise, your provider does not appear to be up-to-date and you changed the path so I can't see if you did that right either. If LINQ Connect Express doesn't work, start with the snippit below.
string connectionString = # "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Your\Full\Path\Database.accdb";
// Create a connection
using(OleDbConnection connection = new OleDbConnection(connectionString)) {
// your code here
}
I wrote a code for my pleasure.
i have access data file "mdb" and i show him on gridview from gridview i select row and shown on text box.
i edit the textbox and try to press on Save button and show me error msg.
what i do wrong?
save button didnt save and show me error msg.
add pictures and my code:
Error msg
gridview+textbox
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.OleDb;
namespace Center image description hereDHW
{
public partial class Form2 : Form
{
private OleDbConnection connection = new OleDbConnection();
public Form2()
{
InitializeComponent();
connection.ConnectionString = #"Provider=Microsoft.Jet.OLEDB.4.0;Data Source = C:\Users\RBA\Desktop\123\users1.mdb;
Persist Security Info=False;";
}
private void button9_Click(object sender, EventArgs e)
{
this.Close();
Form1 f1 = new Form1();
f1.Show();
}
private void btn_save_Click(object sender, EventArgs e)
{
try
{
connection.Open();
OleDbCommand command = new OleDbCommand();
command.Connection = connection;
command.CommandText = "insert into GRL1 (NoBoard,Site,Group,Kind,Unit) values ('" + txt_noboard.Text + "','" + txt_site.Text + "','" + txt_group.Text + "','" + txt_kind.Text + "','" + txt_unit.Text + "',)";
command.ExecuteNonQuery();
MessageBox.Show("Data Saved");
}
catch (Exception ex)
{
MessageBox.Show("Error " + ex);
}
}
private void Form2_Load(object sender, EventArgs e)
{
// TODO: This line of code loads data into the 'users1DataSet.GRL1' table. You can move, or remove it, as needed.
this.gRL1TableAdapter.Fill(this.users1DataSet.GRL1);
}
private void btn_loadGR_Click(object sender, EventArgs e)
{
try
{
connection.Open();
OleDbCommand command = new OleDbCommand();
command.Connection = connection;
string query = "select * from GRL1";
command.CommandText = query;
OleDbDataAdapter da = new OleDbDataAdapter(command);
DataTable dt = new DataTable();
da.Fill(dt);
dataGridView1.DataSource = dt;
connection.Close();
}
catch (Exception ex)
{
MessageBox.Show("Error " + ex);
}
}
private void button3_Click(object sender, EventArgs e)
{
try
{
connection.Open();
OleDbCommand command = new OleDbCommand();
command.Connection = connection;
string query = "select * from GRS1";
command.CommandText = query;
OleDbDataAdapter da = new OleDbDataAdapter(command);
DataTable dt = new DataTable();
da.Fill(dt);
dataGridView1.DataSource = dt;
connection.Close();
}
catch (Exception ex)
{
MessageBox.Show("Error " + ex);
}
}
private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
if (e.RowIndex >= 0)
{
DataGridViewRow row = this.dataGridView1.Rows[e.RowIndex];
txt_noboard.Text = row.Cells[0].Value.ToString();
txt_site.Text = row.Cells[1].Value.ToString();
txt_group.Text = row.Cells[2].Value.ToString();
txt_kind.Text = row.Cells[3].Value.ToString();
txt_unit.Text = row.Cells[4].Value.ToString();
txt_com.Text = row.Cells[5].Value.ToString();
}
}
}
}
You have a typo in your sql text. There is a comma before the close brace. But there is also an error caused by the usage of a reserved keyword in MS-Access (Group). You need to put square brackets around that name.
Finally, do not use string concatenation to build sql commands but always use parameters.
This avoid sql injection hacks and remove problem with parsing your inputs (for example if there is a single quote in your input text the whole query will fail again with a syntax error)
private void btn_save_Click(object sender, EventArgs e)
{
try
{
using(OleDbConnection connection = new OleDbConnection(....con string...))
{
connection.Open();
OleDbCommand command = new OleDbCommand();
command.Connection = connection;
// Notice how Group field is between square brackets.
// If you can I suggest to change the name of this field
string cmdText = #"insert into GRL1 (NoBoard,Site,[Group],Kind,Unit)
values (#nob, #sit, #grp, #knd, #uni)";
command.CommandText = cmdText;
// Is NoBoard an integer? If yes you should pass an integer not a string
command.Parameters.Add("#nob", OleDbType.Integer).Value = Convert.ToInt32(txt_noboard.Text);
command.Parameters.Add("#sit", OleDbType.VarWChar).Value = txt_site.Text;
command.Parameters.Add("#grp", OleDbType.VarWChar).Value = txt_group.Text;
command.Parameters.Add("#knd", OleDbType.VarWChar).Value = txt_kind.Text;
command.Parameters.Add("#uni", OleDbType.VarWChar).Value = txt_unit.Text;
command.ExecuteNonQuery();
MessageBox.Show("Data Saved");
}
}
catch (Exception ex)
{
MessageBox.Show("Error " + ex);
}
}
The parameters collection is filled with the values required by your query text. Notice that I don't know exactly the datatype of your columns in the database. The parameter OleDbType should exactly match the types expected to avoid Type Mismatch exceptions
Last tip. Connections should be created, opened and closed when needed. Do not keep a global connection object. You don't get much gain in performance because ADO.NET employs a technique called Connection Pooling
using MySql.Data.MySqlClient;
The simple connection code with "using":
using (IDbConnection sql = new MySqlConnection(ConnectionString))
{
try
{
sql.Open();
var x = sql.Execute("query...");
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
"Using" calls Dispose(), but if Dispose() calls Close()?
How can I find out if I need to call Close() in MySqlConnection when using?
Do nothing.
Dispose will close connection properly.
From documentation:
Dispose() - Releases all resources used by the MySqlConnection
Form the source code of MySqlConnection.Dispose
void IDisposable.Dispose()
{
if (State == ConnectionState.Open)
Close();
}
Here you can try this, u can put it in a finally clause
if (sql.State == ConnectionState.Open)
{
sql.Close();
}
This is a sample DBConnect class that I am using. With this class, it is really easy to create a database connection anywhere you want. Just create an object of this class.
This is for MySQL database, if you are using sql server just replace MySql with Sql
Here is my DBConnect class
using System ;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using MySql.Data.MySqlClient;
namespace test
{
class DBConnect: IDisposable
{
private static String server = "localhost";
private static String port = "3306";
private static String database = "testDB";
private static String username = "root";
private static String password = "";
private static String connectionString = "Server=" + server + ";Port=" + port + ";Database=" + database + ";Uid=" + username + ";Password=" + password + ";";
public MySqlConnection con = new MySqlConnection(connectionString);
public DBConnect() //Constructor
{
try
{
con.Open();
Console.WriteLine("Database connected");
}
catch (Exception e)
{
Console.WriteLine(e.StackTrace);
Console.WriteLine("Database Connection Failed");
throw new Exception();
}
}
public void Dispose()
{
con.Close();
}
}
}
Here is how you use this class
using(DBConnect db = new DBConnect())
{
String q = "your sql Statement here";
MySqlCommand cmd = new MySqlCommand(q, db.con);
cmd.ExecuteNonQuery();
MessageBox.Show("Item added", "Done", MessageBoxButtons.OK,mesageBoxIcon.Information);
}
I am new on c# and i am facing problem. i made two buttons, one for case another for credit card. when i click on button, my data is not inserting into ms access file.why is it not showing any error and how can i fix it ?
private void CashButton_Click(object sender, EventArgs e)
{
SaveOrder((int)PaymentTypes.Cash);
}
private void CreditCardButton_Click(object sender, EventArgs e)
{
SaveOrder((int)PaymentTypes.CreditCard);
}
private void SaveOrder(int paymentType)
{
try
{
string connstring = ConfigurationManager.ConnectionStrings["dbx"].ConnectionString;
using (OleDbConnection conn = new OleDbConnection(connstring))
{
conn.Open();
using (OleDbCommand cmd = new OleDbCommand("INSERT INTO [Orders](OrderNummber,TransactionDate,ClientName,TotalAmount,PaymentType) VALUES(#OrderNummber,#TransactionDate,#ClientName,#TotalAmount,#PaymentType)",conn))
{
cmd.Parameters.AddWithValue("#OrderNummber",OrderNumberTextBox.Text);
cmd.Parameters.AddWithValue("#TransactionDate",TransactionDateDateTimePicker.Value.Date);
cmd.Parameters.AddWithValue("#ClientName",ClientNameTextBox.Text);
cmd.Parameters.AddWithValue("#TotalAmount",Convert.ToDecimal(TotalAmountTextBox.Text));
cmd.Parameters.AddWithValue("#PaymentType", paymentType);
cmd.ExecuteNonQuery();
}
foreach (DataGridViewRow row in CartDataGridView.Rows)
{
using (OleDbCommand cmd = new OleDbCommand("INSERT INTO [OrdersItems](OrderNumber,Quantity,UnitPrice,TotalPrice) VALUES(#OrderNumber,#Quantity,#UnitPrice,#TotalPrice)", conn))
{
cmd.Parameters.AddWithValue("#OrderNumber", OrderNumberTextBox.Text);
cmd.Parameters.AddWithValue("#Quantity", Convert.ToInt16(row.Cells["Quantity"].Value));
cmd.Parameters.AddWithValue("#UnitPrice",Convert.ToDecimal(row.Cells["UnitPrice"].Value));
cmd.Parameters.AddWithValue("#TotalPrice", Convert.ToDecimal(row.Cells["TotalPrice"].Value));
cmd.ExecuteNonQuery();
}
}
MessageBox.Show("Order is processed successfully!", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
catch (Exception ex)
{
}
}
Do it like this.
using System;
using System.Data;
using System.Windows.Forms;
using System.Data.OleDb;
namespace WindowsFormsApplication2
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
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");
}
}
}
}
This will definitely work. Just change the connection string and the variables to suit your needs.
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?