Can't Update Access database File From C#.NET - c#

I try to learn some coding with Visual C#. I create a form for add and update Access database.
I can successfully add to Access file but I can't update them.
I write a code similar below by some search in internet but I get this error:
ExecuteNonQuery requires an open and available Connection. The connection's current state is closed.
My code is:
public partial class form1 : Form
{
private OleDbConnection con;
private void btnUpDate_Click(object sender, EventArgs e)
{
string FirstName = txtFirstName.Text;
string Family = txtFamily.Text;
string City = txtCity.Text;
string approve = txtapprove.Text;
string OfficeNumber = txtOfficeNumber.Text;
string OfficialDossier = txtOfficialDossier.Text;
string Department = txtDepartment.Text;
string Organization = txtOrganization.Text;
OleDbConnection oleDBConn = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=Data Source=F:\\Database.accdb");
string query = "UPDATE Sheet1 SET FirstName=#FirstName, Family=#Family, City=#City, approve=#approve, OfficeNumber=#OfficeNumber, OfficialDossier=#OfficialDossier, Department=#Department, Organization=#Organization WHERE OfficeNumber=#OfficeNumber";
//string query = "UPDATE aspnet_Users SET FirstName=#FirstName, Family=#Family, City=#City, approve=#approve, OfficeNumber=#OfficeNumber, OfficialDossier=#OfficialDossier, Department=#Department WHERE OfficeNumber=#OfficeNumber";
OleDbCommand cmd = new OleDbCommand(query, oleDBConn);
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("#OfficeNumber", OfficeNumber);
cmd.Parameters.AddWithValue("#OfficialDossier", OfficialDossier);
cmd.Parameters.AddWithValue("#FirstName", FirstName);
cmd.Parameters.AddWithValue("#Family", Family);
cmd.Parameters.AddWithValue("#City", City);
cmd.Parameters.AddWithValue("#approve", approve);
cmd.Parameters.AddWithValue("#Department", Department);
cmd.Parameters.AddWithValue("#Organization", Organization);
try
{
con.Open();
int result = cmd.ExecuteNonQuery();
if (result > 0)
MessageBox.Show("Success!");
else
MessageBox.Show("Sorry!");
}
catch (OleDbException)
{
MessageBox.Show("There is a problem!");
}
finally
{
con.Close();
}
}
}
Where I have mistake? I Don't use of DataSet and DataAdapter. Is problem from there?
I'm using VS 2010

Problem 1: You have not Opened the Connection object oleDBConn which was assigned to the OleDbCommand Object.
You have assigned oleDBConn to OleDbCommand object as below:
OleDbCommand cmd = new OleDbCommand(query, oleDBConn);//here you have assigned oleDbConn
but you have opened different ConnectionObject con as below:
con.Open();
Solution 1:
Replace This: You should always Open the OleDbConnection (oleDBConn) Object which was assigned to the OleDbCOmmand Object.
con.Open();
With This:
oleDBConn.Open();
Problem 2: You have created an Extra connection object con (on top of your btnUpDate_Click function) and by mistake you are working with the same.(Opening and closing the wrong connection object instead of proper one)
Solution 2: Remove the extra connection object created on top of btnUpDate_Click function and replace all con occurences with oleDBConn.
Complete Code:
try
{
oleDBConn.Open();
int result = cmd.ExecuteNonQuery();
if (result > 0)
MessageBox.Show("Success!");
else
MessageBox.Show("Sorry!");
}
catch (OleDbException ex)
{
MessageBox.Show("There is a problem!"+ex.ToString());
}
finally
{
oleDBConn.Close();
}

Related

Update query is not working - help needed

private void Update_Click(object sender, EventArgs e)
{
string loca="Pakistan";
OleDbConnection con = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\\Users\\Usman\\Desktop\\db.accdb");
OleDbCommand com = new OleDbCommand("Update INVENTORY SET Location=? WHERE itemID='1' ", con);
com.Parameters.Add("#loca", OleDbType.VarChar).Value = loca;
con.Open();
try
{
com.ExecuteNonQuery();
}
catch(Exception f)
{
MessageBox.Show(f.Message);
//MessageBox.Show("Given Data is not Valid", "Cannot Add", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
con.Close();
gridview();
}
Here I have changed the code no error m getting is
No value given for one or more required parameters
Update query is not working so please help me with it.
In C# you need to add an actual parameter object and give it a value:
string loca="Pakistan";
OleDbConnection con = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\\Users\\Usman\\Desktop\\db.accdb");
OleDbCommand com = new OleDbCommand("Update INVENTORY SET Location= ? WHERE itemID='1'", con);
com.Parameters.Add("#loca", OleDbType.VarWChar).Value = loca ?? (object)DBNull.Value;
Some other suggestions/habits to get in to:
Wrap your connections and commands in using blocks so that they get disposed of in a timely manner
Do not just catch an exception and show a vague message. Either include the exception details or log it somewhere so that you know what the actual error is.

why isn't my c# insert query working?

what is the problem in my code?
private void button1_Click(object sender, EventArgs e)
{
OleDbConnection conn = new OleDbConnection();
conn.ConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=D:\extract step one\extract1.accdb;Persist Security Info=True";
String kerdes = Convert.ToString(textBox1.Text);
String valaszok = Convert.ToString(textBox2.Text);
OleDbCommand cmd = new OleDbCommand("INSERT into extract (kerdes, valaszok) Values(#kerdes, #valaszok)");
cmd.Connection = conn;
conn.Open();
if (conn.State == ConnectionState.Open)
{
cmd.Parameters.Add("#kerdes", OleDbType.VarChar).Value = kerdes;
cmd.Parameters.Add("#valaszok", OleDbType.VarChar).Value = valaszok;
try
{
cmd.ExecuteNonQuery();
MessageBox.Show("Data Added");
conn.Close();
}
catch (OleDbException ex)
{
MessageBox.Show(ex.Source);
conn.Close();
}
}
else
{
MessageBox.Show("Connection Failed");
}
}
When I click the button it says:
Microsoft Office Access Database Engine
I made the database with Access. Any ideas?
OleDbCommand does not support named parameters - use ? instead:
OleDbCommand cmd = new OleDbCommand("INSERT into extract (kerdes, valaszok) Values(?, ?)");
I would also wrap both the command and connection in using blocks to ensure that the resources are disposed of properly.
You need to change your parameters to:
cmd.Parameters.AddWithValue("#kerdes", kerdes);
cmd.Parameters.AddWithValue("#valaszok", valaszok);
This needs to be done in addition to the above comment of changing your query to:
OleDbCommand cmd = new OleDbCommand("INSERT into extract (kerdes, valaszok) Values(?, ?)");

Unable to access the Microsoft Access database using asp.net and C#

This is code i wrote to add some text to accordion pane on a button click:
protected void Button1_Click1(object sender, EventArgs e)
{
//Use a string variable to hold the ConnectionString.
string connectString = "Provider=Microsoft.Jet.OLEDB.4.0;"
+ "Data Source=D:\\C#Samples\\StudentDetails\\WebRole1\\App_Data\\Students1.accdb";
System.Data.OleDb.OleDbConnection cn = new System.Data.OleDb.OleDbConnection();
cn.ConnectionString = connectString;
//Create an OleDbConnection object, and then pass in the ConnectionString to the constructor.
//OleDbConnection cn = new OleDbConnection(ConfigurationManager.ConnectionStrings["AccessConnectionString"].ConnectionString);
try
{
//Open the connection.
cn.Open();
}
catch (Exception ex)
{
AccordionPane1.Controls.Add(new LiteralControl("Open Error"));
}
string selectString = "SELECT * FROM BasicInfo";
//Create an OleDbCommand object.
//Notice that this line passes in the SQL statement and the OleDbConnection object
OleDbCommand cmd = new OleDbCommand(selectString, cn);
//Send the CommandText to the connection, and then build an OleDbDataReader.
//Note: The OleDbDataReader is forward-only.
try
{
OleDbDataReader reader=null;
try
{
reader = cmd.ExecuteReader();
}
catch (Exception es)
{
AccordionPane1.Controls.Add(new LiteralControl(" datareader"));
}
string s = "s";
reader.Read();
s = reader["S_No"].ToString();
AccordionPane1.Controls.Add(new LiteralControl(s));
//Close the reader and the related connection.
reader.Close();
cn.Close();
}
catch (Exception ex)
{
AccordionPane1.Controls.Add(new LiteralControl(" Read Error"));
}
}
I have my access 2007 database in the folder i specified in the connectString. When im viewing in the browser, on the button click i am getting all the three exceptions:
What might be the problem in opening the database? Do i need to make any other changes?
Change
Provider=Microsoft.Jet.OLEDB.4.0;
to
Provider=Microsoft.ACE.OLEDB.12.0
Provider=Microsoft.ACE.OLEDB.12.0;"
+ "Data Source=D:\\C#Samples\\StudentDetails\\WebRole1\\App_Data\\Students1.accdb
Hopefully it will solve the issue.
you connection string might be cause of isssue
string ConnStr = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=D:\abc.mdb;";
OleDbConnection MyConn = new OleDbConnection(ConnStr);
this For access 2007 also check the path of database is cocrect.
You can use |DataDirectory| instead of real path and you have to change the Provider=Microsoft.ACE.OLEDB.12.0 (as suggested by #MMK)
string connectString = #"Microsoft.ACE.OLEDB.12.0;
Data Source=|DataDirectory|\Students1.accdb;Persist Security Info=False;";
and always use using block which dispose IDisposable objects properly.
using(OleDbConnection cn=new OleDbConnection())
{
using(OleDbCommand cmd=new OleDbCommand())
{
cn.ConnectionString=connectionString;
cmd.CommandText=selectString;
cmd.Connection=cn;
...
}
}

update a mySQL table using C#

I have written some C# to update a MySql table but I get an exception every time I call the method ExecuteNonQuery(). I have researched this on the web and every solution I find produces the same error. I have an open connection to the database and the update query to the database is written correctly. The code that I have so far come up with is :
public int executeUpdate()
{
int result = 0;
if (isConnected)
{
try
{
MySqlConnection cn = new MySqlConnection(connection.ConnectionString);
MySqlCommand cmd = new MySqlCommand();
cmd.Connection = cn;
cmd.CommandText = "UPDATE test SET status_id = 1 WHERE test_id = 1";
int numRowsUpdated = cmd.ExecuteNonQuery();
}
catch (MySqlException exSql)
{
Console.Error.WriteLine("Error - SafeMySql: SQL Exception: " + query);
Console.Error.WriteLine(exSql.StackTrace);
}
catch (Exception ex)
{
Console.Error.WriteLine("Error - SafeMySql: Exception: " + query);
Console.Error.WriteLine(ex.StackTrace);
}
}
else
Console.Error.WriteLine("Error - SafeMySql: executeQuery failed. Not connected to DB");
}
Change your try section to the code below:
try
{
using(MySqlConnection cn = new MySqlConnection(connection.ConnectionString))
{
MySqlCommand cmd = new MySqlCommand();
cmd.Connection = cn;
cmd.CommandText = "UPDATE test SET status_id = 1 WHERE test_id = 1";
cn.Open();
int numRowsUpdated = cmd.ExecuteNonQuery();
cmd.Dispose();
}
}
The connection must be opened before you execute a command. In the example above the command object will immediately be disposed and the connection object will implcitly be closed and disposed when you leave the using section.
I don't see the connection being opened.
Here is an example from MSDN: even inside a using block, they open the connection explicitly
private static void CreateCommand(string queryString,
string connectionString)
{
using (SqlConnection connection = new SqlConnection(
connectionString))
{
SqlCommand command = new SqlCommand(queryString, connection);
command.Connection.Open();
command.ExecuteNonQuery();
}
}
Edit: The principle is the same for MySQL as it is for SQL Server:
public void CreateMySqlCommand(string myExecuteQuery, MySqlConnection myConnection)
{
MySqlCommand myCommand = new MySqlCommand(myExecuteQuery, myConnection);
myCommand.Connection.Open();
myCommand.ExecuteNonQuery();
myConnection.Close();
}

Problem with multiple SqlDataReader and SqlCommand in a Class

I have a problem with C#, I have a Class with a function for SqlDataReader and another for SqlCommand (the first one is just for read values from a DataBase and the second one is for INSERT, UPDATE, DELETE ... in the same DB).
The problem is, for the first part of the code (the login), I have to search the values from an Active Directory (it works), then I must see if the user has username and password in my own DB (it works), and then, if the user is not in the DB then I have to create it and get the ID, if it is already created then I just have to get the ID.
The problem is that I get this message :
InvalidOperationException was
unhandled by user code
There already exist an Open DataReader
associated with this Command, who as
to be closed first.
There is the code :
Class.cs :
private static string MyConnectionString = "THIS IS MY CONNECTION";
private SqlConnection MyConnection = new SqlConnection(MyConnectionString);
public SqlCommand MyCommand = new SqlCommand();
public SqlDataReader MyReader = null;
public void DBMyReader(String SqlQuery)
{
if (MyConnection.State != ConnectionState.Open)
MyConnection.Open();
MyCommand.Connection = MyConnection;
MyCommand.CommandText = SqlQuery;
MyReader = MyCommand.ExecuteReader(CommandBehavior.CloseConnection);
}
public void DBMyUpdate(String SqlQuery)
{
if (MyConnection.State != ConnectionState.Open)
MyConnection.Open();
var cmdTest = new SqlCommand();
cmdTest.Connection = MyConnection;
cmdTest.CommandText = SqlQuery;
cmdTest.ExecuteNonQuery();
}
public void DBMyInsert(String SqlQuery)
{
DBMyUpdate(SqlQuery);
}
** Login.aspx.cs: **
MyClass.DBMyReader("SELECT util_codi,util_logi,util_nome FROM Tgep_util WHERE util_logi='"
+ Session["username"].ToString() + "'");
MyClass.MyReader.Read();
if (!MyClass.MyReader.HasRows)
{
MyClass.MyReader.Close();
MyClass.DBMyInsert("INSERT INTO Tgep_util(util_logi,util_nome) "
+ "VALUES ('" + Session["username"].ToString() + "','" + Session["nome"].ToString() + "')");
}
MyClass.DBMyReader("SELECT util_codi,util_logi,util_nome FROM Tgep_util WHERE util_logi='"
+ Session["username"].ToString() + "'");
MyClass.MyReader.Read();
Session["user_id"] = MyClass.MyReader["util_codi"].ToString();
Response.Redirect("FRM_Principal.aspx");
Edit : Update Code (Works for now)
The error means exactly what it says.. You have loaded a SQLCommand and started reading rows, and are now trying to do an insert. You need to close out that reader first, or use a new command.
in the DBMyUpdate function you could just create a new command:
public void DBMyUpdate(String SqlQuery)
{
if (MyConnection.State != ConnectionState.Open)
MyConnection.Open();
var cmdUpdate = new SqlCommand();
cmdUpdate.Connection = MyConnection;
cmdUpdate.CommandText = SqlQuery;
cmdUpdate.ExecuteNonQuery(CommandBehavior.CloseConnection);
}
edit: based on comments to this answer, it required using separate connections which seems odd/incorrect.
You can't use the same DataReader for insert/update that you used for insertion. You have to close the DataReader first before associating some other command with the DataReader.

Categories

Resources