C# to MySqlDB update - c#

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

Related

C# Databases SQLite Locked Database Error

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.

MySql Update won't work

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

Execute Datetime from C# to date in SQL Server 2008

I'm new in programming and want you to help me.
I have field of type (date) and when I insert data to database from my website in visual studio 2010 with C#, it Shows me an error during execution.
Can anyone help me?
Thank you
Code behind
string InsMus = "Insert into StoreMus (MusNo,MusDate)" +
"Values (" + Convert.ToInt16(txtMusNo.Text) + ",'" + DateTime.Parse(txtMusDate.Text) + "')";
cmd = new SqlCommand(InsMus , con);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
Don't use string concanation to prevent sql injection. I'm sure that it will also fix this issue.
string InsMus = #"Insert into StoreMus (MusNo,MusDate)
Values (#MusNo, #MusDate);";
using(var con = new SqlConnection("Connection String..."))
using(var cmd = new SqlCommand(InsMus, con))
{
cmd.Parameters.Add("#MusNo", SqlDbType.SmallInt).Value = short.Parse(txtMusNo.Text);
cmd.Parameters.Add("#MusDate", SqlDbType.Date).Value = DateTime.Parse(txtMusDate.Text);
con.Open();
int inserted = cmd.ExecuteNonQuery();
}
Note that i've used the using-statement to ensure that the connection gets disposed/closed.
You could also use DateTime.TryParse instead of DateTime.Parse to prevent an exception that happens when the format of the date is invalid:
DateTime musDate;
if(!DateTime.TryParse(txtMusDate.Text, out musDate))
{
MessageBox.Show("Please enter a valid mus-date.");
return;
}
// here you can use musDate

error for insert and stored data in access 2013

i have this code for insert data into access 2013
after click in the save button data insert into dataGridView and show
and when stop program and restart this,data not stored in the DB.I've done a lot of searches but can't find the solution. my class code and my button save code
class DB
{
public static OleDbConnection con = new OleDbConnection();
static DB()
{
con.ConnectionString = "Provider=MICROSOFT.ACE.OLEDB.12.0; " +
"Data Source=|DataDirectory|//Phonebook-db.accdb;Persist Security Info=True";
}
public static void Insert(Person p1)
{
try
{
OleDbCommand cmd = con.CreateCommand();
con.Open();
string s = "INSERT INTO Industrialist (S_Name,S_Family,S_Telephone,S_Major)VALUES('" + p1.Name + "','" + p1.Family + "','" + p1.Telephone + "','" + p1.Major + "')";
cmd.CommandType = CommandType.Text;
cmd.CommandText = s;
cmd.ExecuteNonQuery();
con.Close();
System.Windows.Forms.MessageBox.Show("Record successfully Added");
}
catch (OleDbException exp) { MessageBox.Show(exp.ToString()); }
}
}
Person p = new Person();
p.Name = txtname.Text;
p.Family = txtfamily.Text;
p.Telephone = txttell.Text;
p.Major = txtmajor.Text;
DB.Insert(p);
txttell.Text = "";
txtmajor.Text = "";
txtname.Text = "";
txtfamily.Text = "";
List<Person> people = DB.GetPeople();
dataGridView1.DataSource = people;
Choose your ACCDB file listed in your project files, select Copy To Output Directory and set its value to Never (And remember that |DataDirectory| is a substitution strings that points (for ASP.NET projects) to APP_DATA, your record is inserted in the database copied in that directory.
Said that please consider to use a parameterized query to create an sql command, not string concatenations
try
{
OleDbCommand cmd = con.CreateCommand();
con.Open();
string s = "INSERT INTO Industrialist (S_Name,S_Family,S_Telephone,S_Major)VALUES(" +
"?,?,?,?)";
cmd.CommandText = s;
cmd.Parameters.AddWithValue("#p1",p.Name);
cmd.Parameters.AddWithValue("#p2",p.Family);
cmd.Parameters.AddWithValue("#p3",p.Telephone);
cmd.Parameters.AddWithValue("#p4",p.Major);
cmd.ExecuteNonQuery();
con.Close();
System.Windows.Forms.MessageBox.Show("Record successfully Added");
}
catch (OleDbException exp) { MessageBox.Show(exp.ToString()); }
Of course do not close the connection before executing the command.
Another point to change is the usage pattern of your connection. Do not create a global connection and keep it around for the lifetime of your application. Simply create and use it when needed and close/dispose immediately after
using(OleDbConnection con = new OleDbConnection("Provider=MICROSOFT.ACE.OLEDB.12.0; " +
"Data Source=|DataDirectory|//Phonebook-db.accdb;" +
"Persist Security Info=True"))
{
try
{
OleDbCommand cmd = con.CreateCommand();
....
}
} // <- Here at the closing brace the connectio will be close and disposed

MySQL Query with MySQLParameters in C#

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.

Categories

Resources