private void button4_Click(object sender, EventArgs e)
{
MySqlConnection connection = new MySqlConnection("datasource=localhost;port=3306;Initial Catalog='liblib';Data Source=localhost;username=root;password=admin");
String query = "UPDATE loans SET dataRet=#data1 WHERE loans.idloans = #idloan";
MySqlCommand cmd = new MySqlCommand(query, connection);
int id = Int32.Parse(textBox9.Text);
cmd.Parameters.Add("#data1", MySqlDbType.Date).Value = dateTimePicker1.Value;
cmd.Parameters.Add("#idloan", MySqlDbType.Int32).Value = id;
connection.Open();
if (cmd.ExecuteNonQuery() == 1)
{
MessageBox.Show("Succesful!");
connection.Close();
FIllCard();
}
else
{
MessageBox.Show("Error");
connection.Close();
}
When I execute this UPDATE query in phpmyadmin it works and updates the entry:
UPDATE loans SET dataRet='2017-5-6' WHERE loans.idloans = 23.
But the problem is when I try it in my Form whith parameters. It always returns me "Error" message(ExecuteNonQuery is different from 1), and when I check the database there is no update. The type of the variables in my database are:
idloans - int; dataRet = date;
Check out this post: update a mySQL table using C#, It does not have an answer marked as solution, but the OP of that question has authentication problems after using the code of the first answer, perhaps it works for you
Related
When I enter a number in the ChbBeds_numericUpDown and click on the "Update" button, it says "Data Updated", but nothing changes in the database
private void ChbUp_button_Click(object sender, EventArgs e)
{
try
{
string statement = "UPDATE ChamberXPavilions SET Beds count = #beds_count WHERE Pav_name = #pav_name AND Chamber_number = #chamber_number";
cmd = new OleDbCommand(statement, conn);
cmd.Parameters.AddWithValue("#pav_name", Chbpav_comboBox.Text);
cmd.Parameters.AddWithValue("#chamber_number", Chb_numericUpDown.Value);
cmd.Parameters.AddWithValue("#beds_count", ChbBeds_numericUpDown.Value);
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
MessageBox.Show("Data updated");
showdata();
}
catch(Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
Is the SQL statement wrong ?
Contrary to SQL Server, the OleDB provider for MS Access does NOT work with named parameters - instead, it uses positional parameters.
In your case, you have a SQL statement
UPDATE ChamberXPavilions
SET Beds count = #beds_count
WHERE Pav_name = #pav_name AND Chamber_number = #chamber_number
so you need to also provide the parameters in the same order - first #beds_count, then #pav_name and finally #chamber_number.
So try this for providing the parameter values:
cmd = new OleDbCommand(statement, conn);
cmd.Parameters.AddWithValue("#beds_count", ChbBeds_numericUpDown.Value);
cmd.Parameters.AddWithValue("#pav_name", Chbpav_comboBox.Text);
cmd.Parameters.AddWithValue("#chamber_number", Chb_numericUpDown.Value);
Now, your UPDATE statement should get the proper values and should now work
When i run my code in the debugger and I hover my mouse over the parameters they do have the right values in them. It just doesn't update my database but when I copy the query and put it into the database it works without a problem.
The parameter values are:
id = 7
omschrijving = douche muntjes
prijs = 0,5
catagorie = faciliteiten
I checked the connection tring by using an insert query and that does add records to my database. And There is an id with the value of 7 in the database.
When I run a insert query or a delete query through my C# code it does work it's just the update statement that doesn't work. If anyone sees the issue please help me.
public static void wijzigprijs(int id, string omschrijving, decimal prijs, string catagorie)
{
try
{
try
{
OleDbConnection verbinding = new OleDbConnection(
#"Provider=Microsoft.ACE.OLEDB.12.0;
Data Source=..\..\..\La_Rustique.accdb;
Persist Security Info=False;");
verbinding.Open();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
OleDbCommand query = new OleDbCommand();
query.CommandText = #"UPDATE prijslijst
SET omschrijving = #omschrijving,
prijs = #prijs,
catagorie = #catagorie
WHERE id = #id";
query.Parameters.Add(new OleDbParameter("#id", OleDbType.Integer));
query.Parameters["#id"].Value = id;
query.Parameters.Add(new OleDbParameter("#omschrijving", OleDbType.VarChar));
query.Parameters["#omschrijving"].Value = omschrijving;
query.Parameters.Add(new OleDbParameter("#prijs", OleDbType.Decimal));
query.Parameters["#prijs"].Value = prijs;
query.Parameters.Add(new OleDbParameter("#catagorie", OleDbType.VarChar));
query.Parameters["#catagorie"].Value = catagorie;
query.Connection = verbinding;
query.ExecuteNonQuery();
MessageBox.Show("succesvol gewijzigd");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
verbinding.Close();
}
}
EDIT UPDATE
Look at this topic. Here he explains how you should use variables with OleDbCommand
Variables with OleDbCommand
This is how you typically will do it when using SQLCommand parameters:
I know this doesnt answer your questions quite, but when i use SQLCommand i use this code whenever i want to update or insert with variables:
string query = #"UPDATE prijslijst
SET omschrijving = #omschrijving,
prijs = #prijs,
catagorie = #catagorie
WHERE id = #id";
SqlCommand cmd = new SqlCommand(query, connDatabase);
cmd.Parameters.Add("#id", SqlDbType.integer).Value = 7;
cmd.ExecuteNonQuery();
connDatabase.Close();
So you should be able to do the samething. Hope this will help you.
I have never seen OleDB queries written in the above syntax.
To state it differently: OleDB simply does not use named parameters, it uses the position only.
Try to change your SQL statement like this:
query.CommandText = #"UPDATE prijslijst
SET omschrijving = ?,
prijs = ?,
catagorie = ?
WHERE id = ?";
and then add the parameters in sequence of above in the code
below that.
Sorry guys to my english..
when i insert a record the same description with the existing record in datagridview but different quantity.. it creates a new row for the last record i inserted...
what i want is to ADD the quantity i inserted to the old record with the same description..
1. HERE'S THE IMAGE FOR YOU TO UNDERSTAND THE PROBLEM
2. THIS IS WHAT HAPPEN
The result should be QUANTITY = 25.. and also the totalcbm.. totalcbm = quantity * cbm
private void btnSave_Click(object sender, EventArgs e)
{
MySqlConnection connection = new MySqlConnection(MyConnectionString);
MySqlCommand cmd;
connection.Open();
try
{
cmd = connection.CreateCommand();
cmd.CommandText = "INSERT INTO Inventory(Quantity,Unit,ItemCode,ItemName,Cbm,TotalCbm)VALUES(#Quantity,#Unit,#ItemCode,#ItemName,#Cbm,#TotalCbm)";
cmd.Parameters.AddWithValue("#Quantity", tbQuantity.Text.ToString());
cmd.Parameters.AddWithValue("#Unit", tbUnit.Text.ToString());
cmd.Parameters.AddWithValue("#ItemCode", tbItemCode.Text.ToString());
cmd.Parameters.AddWithValue("#ItemName", tbItemName.Text.ToString());
cmd.Parameters.AddWithValue("#Cbm", tbCbm.Text.ToString());
cmd.Parameters.AddWithValue("#TotalCbm", tbTotalCbm.Text.ToString());
cmd.ExecuteNonQuery();
}
catch (Exception)
{
throw;
}
finally
{
if (connection.State == ConnectionState.Open)
{
connection.Close();
frmUserAE form1 = new frmUserAE();
AccountForm.LoadGrid();
this.Hide();
}
}
}
You are doing an INSERT statement, which will create a new row.
You should do an UPDATE statement, depending on what you think is your primary key (the description?).
I've created a website that is connected to the database, I can get data and display it on the page with no prob at all. But when I try to insert (or update) it does nothing.
I have tested the SQL query and it works just fine.
I've looked here for similar situations and questions here for the past 24 hours with no luck.
I want the website to tell if the user want a one way or two way tickets and make a request. The table has the request id which is automatically incremented
then I add the id of the student who is requesting, the the id of the departure ticket then the id of return ticket (if it is 2 ways, this value can be null) there is also status which will be pending until a supervisor either accept or decline the request, once accepted, issue date will be added and status will change to approved. If declined reason will be added and status change to declined.
Main issue, when I make the request, the row is not created and added to the database for the supervisor to view later.
Here is my code:
protected void Button1_Click(object sender, EventArgs e)
{
int parsedValue;
int.TryParse(DropDownList1.SelectedValue, out parsedValue);
SqlConnection myConnection = new SqlConnection(""); // I removed the connection string.
string sqlcommand = "";
string idString = TextBox1.Text;
string idTwoString ="";
bool canContune = false;
if (parsedValue == 1)
{
System.Diagnostics.Debug.WriteLine("p");
Panel3.Visible = true;
idTwoString = TextBox2.Text;
if (AllNumber(idString, TextBox1) && AllNumber(idTwoString, TextBox2))
{
canContune = true;
}
}
else if (AllNumber(idString, TextBox1))
{
canContune = true;
}
if (canContune)
{
int dId;
int dId2;
int.TryParse(idString, out dId);
int.TryParse(idTwoString, out dId2);
sqlcommand = "INSERT INTO TicketRequest.dbo.TicketRequest (student_id, departure_id, return_id, statues, issue_date, notes) "
+ "VALUES (#student_id, #departure_id , #return_id , #statues, #issue_date, #notes)";
try
{
SqlCommand cmd = new SqlCommand(sqlcommand);
cmd.CommandType = CommandType.Text;
cmd.Connection = myConnection;
myConnection.Open();
cmd.Parameters.Add("#student_id", SqlDbType.Int).Value = id;
cmd.Parameters.Add("departure_id", SqlDbType.Int).Value = dId; //I used AddWithValue(#para, value) it didn't work.
if (parsedValue == 0)
{
cmd.Parameters.AddWithValue("#return_id", DBNull.Value);
}
else
{
cmd.Parameters.Add("#return_id", SqlDbType.Int).Value = dId2;
}
cmd.Parameters.Add("#statues", SqlDbType.Text).Value = "Pending";
cmd.Parameters.AddWithValue("#issue_date", DBNull.Value);
cmd.Parameters.AddWithValue("#notes", DBNull.Value);
cmd.ExecuteNonQuery();
myConnection.Close();
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine(ex.ToString());
}
}
}`
It doesn't throw any exception, I really don't know what is wrong.
I would be very thankful to anyone who will point me out my mistake in Insert query. Thanks in advance.
==================================================
I apologized all, it worked just fine. it seemed that the code wasn't excuted to being with. Thanks Falanor, you helped me discover the problem. =)
Try to check the return value.
int modified =(int)cmd.ExecuteScalar();
This is also missing the # symbol for the parameter
cmd.Parameters.Add("departure_id", SqlDbType.Int).Value = dId; //I used AddWithValue(#para, value) it didn't work.
I am Nubie in C#, I Try to learn CRUD. Select data Succes but I cant Save data to mysql.
my table
mahasiswa
ID| namae | jurusan | email
_____________________________
1 | Bill | IT | bill#gmail.com
2 | Tony | IT | Tony#gmail.com
ID is set to auto increment in Mysql
and this my script for btn save
void btnsave_Click(object sender, EventArgs e)
{
try
{
if (txtid.Text != "" && txtnama.Text != "" && txtjurusan.Text != "" && txtemail.Text != "")
{
query = string.Format("INSERT INTO mahasiswa values ('{1}','{2}','{3}');", txtnama.Text, txtjurusan.Text, txtemail.Text);
koneksi.Open();
perintah = new MySqlCommand(query, koneksi);
adapter = new MySqlDataAdapter(perintah);
int res = perintah.ExecuteNonQuery();
koneksi.Close();
if (res == 1)
{
MessageBox.Show("Input Data Sukses...");
}
else
{
MessageBox.Show("Input Data Gagal... ");
}
}
else
{
MessageBox.Show("Data tidak lengkap");
}
}
catch(Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
That Script can run, but after input data and click save buttonm the program stop.
Can anybody help me.
Im very Appreciated your answer
Thanks
form load
void Form1_Load(object sender, EventArgs e)
{
try
{
koneksi.Open();
query = string.Format("SELECT * FROM mahasiswa");
perintah = new MySqlCommand(query, koneksi);
adapter = new MySqlDataAdapter(perintah);
perintah.ExecuteNonQuery();
ds.Clear();
adapter.Fill(ds);
koneksi.Close();
dgv1.DataSource = ds.Tables[0];
dgv1.Columns[0].Width = 50;
dgv1.Columns[0].HeaderText = "ID";
dgv1.Columns[1].Width = 120;
dgv1.Columns[1].HeaderText = "Nama Mahasiswa";
dgv1.Columns[2].Width = 120;
dgv1.Columns[2].HeaderText = "Jurusan";
dgv1.Columns[3].Width = 120;
dgv1.Columns[3].HeaderText = "Email";
//txtid.clear();
txtnama.Clear();
txtjurusan.Clear();
txtemail.Clear();
btnedit.Enabled = false;
btndelete.Enabled = false;
btnsave.Enabled = true;
btnsearch.Enabled = true;
}
catch (Exception ex) {
MessageBox.Show(ex.ToString());
}
}
Also if your learning CRUD it would be helpful if you made the necessary stored procedures within SQL aswell as attempting it this way.
Just create a CREATE, INSERT, UPDATE, DELETE procedure. Then in your code for an insert example you have this:
public bool Add(string example)
{
try
{
using (SqlConnection con = new SqlConnection(connectionString))
{
SqlCommand cmd = new SqlCommand("[Proc name]", con);
cmd.CommandType = CommandType.StoredProcedure;
if (con.State == ConnectionState.Closed)
con.Open();
cmd.Parameters.AddWithValue("#Example", example);
cmd.ExecuteNonQuery();
return true;
}
}
This allows you to view what happens and to ensure your procedures are working correctly. This way allows you to catch exceptions easier, and also validate your inputs easier.
try this
"INSERT INTO mahasiswa (name,jurusan,mail) values ('{1}','{2}','{3}')", txtnama.Text, txtjurusan.Text, txtemail.Text)";
as your query will instruct mysql to look for 4 values whereas you are passing only 3 values.
Do not use string concatenation to build sql command text, use always a parameterized query
query = "INSERT INTO mahasiswa VALUES (#p1,#p2,#p3);";
using(MySqlConnection koneksi = new MySqlConnection(connectionString))
using(MySqlCommand perintah = new MySqlCommand(query, koneksi))
{
koneksi.Open();
perintah.Parameters.AddWithValue("#p1", txtnama.Text);
perintah.Parameters.AddWithValue("#p2", txtjurusan.Text);
perintah.Parameters.AddWithValue("#p3", txtemail.Text);
int res = perintah.ExecuteNonQuery();
if (res == 1)
MessageBox.Show("Input Data Sukses...");
else
MessageBox.Show("Input Data Gagal... ");
}
If you use string concatenation your code will be open to sql injection where a malicious user could wreak havoc with your database (Look at this funny example)
Also your format statement is totally wrong, I doubt that your code reaches the point where the database command is executed because you list the arguments for string.Format from the index 1 to index 3 and you supply 3 arguments, but the index should start from zero and end at two. So you should get an exception on that line.
Another point to keep note is the using statement. As you can see, in my code the using statement will ensure the proper closing and disposing of the connection and command objects. The connection is particularly important to dispose properly because a failure here could break your program later.