I am currently writing a code using C# and SQLite. There is an error being throwing stating that the database is locked twice in a message box.
The query works on SQLite DB Browser however, when it is placed in C# code it throws the error.
Here is the code that is giving me an error:
cmd.CommandText = "UPDATE customers SET Bill = Bill - "+textBox2.Text+" WHERE customers.CustomerID = " + textBox1.Text + ";";
There seems to be an issue with the equals sign, might be something wrong with the arithmetic process.
Complete code:
SQLiteConnection myconn = new SQLiteConnection(#"Data Source = C:\Users\chick\Newspaper.db");
SQLiteCommand cmd = myconn.CreateCommand();
cmd.CommandText = "UPDATE customers SET Bill = (Bill - "+textBox2.Text+") WHERE customers.CustomerID = " + textBox1.Text + ";";
myconn.Open();
try
{
cmd.ExecuteNonQuery();
MessageBox.Show("Succesfully Update");
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
UPDATE:
Changed format to using() {} however it is still not working. Program is crashing
New Code:
using (SQLiteConnection myconn = new SQLiteConnection(#"Data Source = C:\Users\chick\Newspaper.db"))
{
var sql = "Update customers SET Bill = Bill - #pay WHERE customers.CustomerID = #cid;";
myconn.Open();
using (var cmd = new SQLiteCommand(sql, myconn))
{
cmd.Parameters.AddWithValue("#cid", textBox1.Text);
cmd.Parameters.AddWithValue("#pay", textBox2.Text);
cmd.ExecuteNonQuery();
}
}
The problem is that some other part of the program (or some other program) still has an active transaction.
You must properly clean up all commands that access the database, i.e., use using everywhere.
Thank you to all that have answered. We realized the issue was that we never closed the reader in previous code.
Related
I'm currently working on a little example for a friend to record employers working time. Therefore I want to update the record of a MySQL database.
The connection to the DB is already done and is working on the test, however, I do not manage (and yes I googled a lot) to actually get the values changing in the DB. This is my current attempt to give out the current time for when employers start working:
void main(string[] args)
{
// Die Verbindung zur DB entnehmen.
MySqlConnection conn = DBUtils.GetDBConnection();
conn.Open();
try
{
// Der Befehl UPDATE.
string sql = "UPDATE user SET lastlogin = lastlogin WHERE user username = srademacher";
MySqlCommand cmd = new MySqlCommand();
cmd.Connection = conn;
cmd.CommandText = sql;
MySqlParameter lastlogin = new MySqlParameter("#lastlogin", SqlDbType.DateTime);
lastlogin.Value = DateTime.Now;
cmd.Parameters.Add(lastlogin);
// Command durchführen
int rowCount = cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
Console.WriteLine("Error: " + e);
}
finally
{
conn.Close();
conn.Dispose();
conn = null;
}
Console.Read();
MessageBox.Show("Die Arbeit wurde um " + DateTime.Now + " aufgenommen");
}
I guess you could call me a noob at scripting but I would be happy to get some advice to become better :-) thank you for your ideas.
Edit: I do not have any problems launching the application the code accords to, just the DateTime Value in DB does not change
Your update statement has incorrect syntax, WHERE user username = srademacher. Then you add MySqlParameter but not using that in sql.
Change sql to
string sql = "UPDATE user SET lastlogin = #lastlogin WHERE username = #username";
and add
MySqlParameter username = new MySqlParameter("#username", SqlDbType.NVarChar);
username.Value = "srademacher";
cmd.Parameters.Add(username);
Good day! I need help please..
This is my code on c# whenever I execute it nothing happens no error or hint
string myConnection = " datasource=localhost;port=3306;username=root;password=wolf";
string Query = " UPDATE bikerentaldb.tblbikes SET status='Rented',renteddate=NOW(),assignedreturndate='" + txtToBeReturned.Text + "' WHERE bikeID='" + txtBikeIdRent.Text + "'";
MySqlConnection myConn = new MySqlConnection(myConnection);
MySqlCommand SelectCommand = new MySqlCommand(Query, myConn);
myConn.Open();
MessageBox.Show("Data Saved");
myConn.Close();
I am not sure why the Upate won't work but when I execute this code on MySql
UPDATE bikerentaldb.tblbikes SET status='Rented',renteddate=NOW(),assignedreturndate=NOW() WHERE bikeID='2';
It works just fine can someone help me?
A command should be executed to do anything. Your code misses the call to SelectCommand.ExecuteNonQuery() line after the open connection. However after fixing this trivial error you could encounter other problems with the values concatenated to form your command text. What if the user types an invalid date? Have you ever heard of Sql Injection hacks?
This is how your code should be written after adding validation to your inputs and parameters to send values to your database
int bikeID = 0;
if(!Int32.TryParse(txtBikeIdRent.Text, out bikeID)
{
MessageBox.Show("Invalid number");
return;
}
DateTime returnDate;
if(!DateTime.TryParse(txtToBeReturned.Text , out returnDate)
{
MessageBox.Show("Invalid date");
return;
}
string myConnection = ".....";
string Query = #"UPDATE bikerentaldb.tblbikes
SET status='Rented', renteddate=NOW(),
assignedreturndate=#date
WHERE bikeID=#id";
using(MySqlConnection myConn = new MySqlConnection(myConnection))
using(MySqlCommand cmd = new MySqlCommand(Query, myConn))
{
myConn.Open();
cmd.Parameters.Add("#date", MySqlDbType.Date).Value = returnDate;
cmd.Parameters.Add("#id", MySqlDbType.Int32).Value = bikeID;
int rowUpdated = cmd.ExecuteNonQuery();
if(rowUpdated > 0)
MessageBox.Show("Record updated");
else
MessageBox.Show("No record match");
}
I'm currently working on a simple windows form bug reporter for university and am having trouble. I'm trying to create a query where the user can only delete the bug if:
The bug name exists
The user logged in matches the user that reported the bug.
Currently no matter which use is logged in, the query always returns 'Incorrect User Logged In!' and doesn't delete the bug.
I am a novice at both C# and MySQL, so I'm sure my code isn't the best way of writing it. I apologize if it is hard to read.
EDIT
Here is my current code based on the below answer which still doesnt work. I currently get could not find specified colum in results: bug_submitted_by
connection = new MySqlConnection(connectionString);
string check = "SELECT COUNT(*) FROM bugs WHERE bug_name ='" + this.txt_bug_name.Text + "'AND bug_submitted_by='" + this.lbl_user.Text + "';";
MySqlCommand cmd = new MySqlCommand(check, connection);
MySqlDataReader reader;
connection.Open();
reader = cmd.ExecuteReader();
if (reader.Read())
{
if (reader.GetString("bug_submitted_by").Equals(this.lbl_user.Text))
{
reader.Close();
cmd.Dispose();
string query = "DELETE from bugs WHERE bug_name='" + this.txt_bug_name.Text + "';";
MySqlCommand cmd2 = new MySqlCommand(query, connection);
MySqlDataReader reader2;
reader2 = cmd2.ExecuteReader();
lbl_message.Text = "Bug Deleted!";
reader2.Close();
cmd2.Dispose();
connection.Close();
load_table();
Combo_selection();
reset(this);
}
else
{
lbl_message.Text = "Incorrect user!";
reader.Close();
cmd.Dispose();
connection.Close();
cb_names.SelectedIndex = -1;
}
}
else
{
lbl_message.Text = "Bug Doesn't Exist!";
}
As a side note first, I recommend you look into parameterized queries in C#. I will use that sort of syntax in my answer, but I believe it will be easy enough for you to understand. Given that you are trying to do multiple things (check if bug exists, check if bug was written by that user, delete that bug if condition is met) I recommend you break it up into pieces and put them all back together.
To start, we can just write a query to see if a bug exists. We can be smart and select both the bug name, and who it was submitted by:
using(var conn = new MySqlConnection(ConnectionString)
{
conn.Open();
using(var cmd = new MySqlCommand())
{
cmd.Connection = conn;
cmd.CommandText = "SELECT bug_name, bug_submitted_by FROM bugs WHERE bug_name = #name";
cmd.Parameters.AddWithValue("#name", this.txt_bug_name.Text);
using(var reader = cmd.ExecuteReader())
{
if(reader.Read())
{
// Will fill in next
}
}
}
}
Side note: If you're unfamiliar with using, see this question for some insight. This is so you don't have to worry about disposing the objects, they will be disposed once you leave scope of the using block.
So, the above query pulls the row from the table where the bug name matches the input. The inner if statement is used to make sure a row was returned. If it was, check the username and react accordingly. If it doesn't, react accordingly like this:
using(var conn = new MySqlConnection(ConnectionString)
{
conn.Open();
using(var cmd = new MySqlCommand())
{
cmd.Connection = conn;
cmd.CommandText = "SELECT bug_name, bug_submitted_by FROM bugs WHERE bug_name = #name";
cmd.Parameters.AddWithValue("#name", this.txt_bug_name.Text);
using(var reader = cmd.ExecuteReader())
{
if(reader.Read())
{
// We got a row
if(reader.GetString("bug_submitted_by").Equals(this.lbl_user.Text))
{
// If the username matches delete it
using(var cmd2 = new MySqlCommand())
{
cmd2.Connection = conn;
cmd2.CommandText = "DELETE FROM bugs WHERE bug_name = #name";
cmd2.Parameters.AddWithValue("#name", this.txt_bug_name.Text);
cmd2.ExecuteNonQuery();
lbl_message.Text = "Bug Deleted!";
}
}
else
{
// Username doesn't match
lbl_message.Text = "Incorrect user!";
}
}
else
{
// We didn't get a row
lbl_message = "Bug Doesn't Exist!";
}
}
}
}
What this query does not do is protect against the situation where a specific bug name appears twice. If your database restricts that, then you're good. If it doesn't, you'll need to implement some check to make sure you only got one row back.
Please don't hit database with subsequent requests. Not only this unnecessary but may also be misleading because a lot may happen between two calls that you make in a multiuser environment. Another session may already updated or deletes this row.
You can do it all in one go
DELETE
FROM bugs
WHERE bug_name = 'bug1'
AND bug_submitted_by = 'John';
Here is a SQLFiddle demo
This code connect to oracle but not execute query.
I install Oracle Developer Tools for Visual Studio .NET.
And check code is true.
And Oracle.DataAccess.dll.
And It works query in sql developer.
And everything code is true but not execute statement .
help me.
bool result = false;
string connst =System.Configuration.ConfigurationSettings.AppSettings["OISCS"];
Console.Write(connst);
OleDbConnection dbConn = new OleDbConnection();
dbConn.ConnectionString = connst;
OleDbCommand dbCom = new OleDbCommand(" SELECT * FROM OIS.USERINFo WHERE USERID= '" + UserID + "';", dbConn);
dbCom.CommandType = System.Data.CommandType.Text;
dbCom.CommandTimeout = 30;
try
{
dbConn.Open();
OleDbDataReader dbReader = (OleDbDataReader)dbCom.ExecuteReader();
dbReader.Read();
}
catch (Exception e)
{
throw e;
}
return result;
You should change the lines where you initialize the dbReader:
OleDbDataReader dbReader = (OleDbDataReader) dbCom.ExecuteReader();
The code you have now throws a NullReferenceException because you never initialize dbReader.
UPDATE: Now that the question is updated, this should no longer be the case...
I am currently developing an Application for Windows using MySQL and C#. I have the following code:
private void cboCategories_SelectedIndexChanged(object sender, EventArgs e)
{
DatabaseWork dbase = new DatabaseWork();
try
{
dbase.openConnection();
string query = "SELECT * FROM budgetcategory WHERE budc_userID=#userID AND budc_category=#category";
MySqlCommand cmd = new MySqlCommand("", dbase.conn);
cmd.CommandText = query;
cmd.Parameters.AddWithValue("#userID", userID);
cmd.Parameters.AddWithValue("#category", cboCategories.SelectedItem.ToString());
MySqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
setCatId(reader.GetString("budc_category_id"));
Console.WriteLine("Category ID: " + getCatId());
}
}
catch (MySqlException ex)
{
Console.WriteLine("Cat Error: " + ex.Message);
}
finally
{
dbase.closeConnection();
}
}
For some reason when I debug the code it never goes into the while loop as if nothing was ever returned from the database. But I know there should be something in there.
Thanks for any help you can provide
Just trying to help you debug a little:
Try reducing these three lines:
string query = "SELECT * FROM budgetcategory WHERE budc_userID=#userID AND budc_category=#category";
MySqlCommand cmd = new MySqlCommand("", dbase.conn);
cmd.CommandText = query;
to just:
string query = "SELECT * FROM budgetcategory WHERE budc_userID=#userID AND budc_category=#category";
MySqlCommand cmd = new MySqlCommand(query, dbase.conn);
Now put a breakpoint on those lines that add the parameters, and make sure that userID and especially cboCategories.SelectedItem.ToString() have the values that you expect.
Also, can you confirm that no exception is thrown?
If this is not the case run the query, with those exact values directly against the database and confirm that something is returned.