how to update selected data in mysql in c#?
this is my code when i press button2 . all data "jumlah_product" minus two.
i want to make just minus two "jumlah_product" in selected data.
private void button2_Click_1(object sender, EventArgs e)
{
string MyConnectionString = "Server=localhost;Database=maindata;Uid=root;pwd=firmandoang;";
string Query = "select * from maindata.product_database where idproduct = '" + this.textBox1.Text + "' OR namaproduct LIKE '" + this.textBox1.Text + "'";
MySqlConnection conn = new MySqlConnection(MyConnectionString);
MySqlCommand command = new MySqlCommand(Query, conn);
MySqlDataReader myReader;
conn.Open();
myReader = command.ExecuteReader();
try
{
if (myReader.Read())
{
DataGridViewRow row = (DataGridViewRow)dataGridView1.Rows[0].Clone();
row.Cells[1].Value = myReader.GetString("namaproduct");
row.Cells[2].Value = myReader.GetString("hargaproduct");
int count = Convert.ToInt32(textBox2.Text);
int price = Convert.ToInt32(row.Cells[2].Value);
row.Cells[3].Value = count;
row.Cells[4].Value = price *= count;
dataGridView1.Rows.Add(row);
string update = "UPDATE maindata.product_database SET jumlah_product=(jumlah_product - '" + count + "')";
MySqlCommand cmd = new MySqlCommand(update, conn);
MySqlDataReader reader;
myReader.Close();
reader = cmd.ExecuteReader();
reader.Close();
conn.Close();
}
else
{
MessageBox.Show("No Data ");
}
sorry for bad english . I hope you understand :)
Related
This is the login page that has the credentials the user enters while logging in.
private void simpleButton1_Click(object sender, EventArgs e)
{
try
{
string myConnection = "datasource = localhost;database = imprest system;port = 3306;username = root;password = ''";
MySqlConnection myConn = new MySqlConnection(myConnection);
MySqlCommand SelectCommand = new MySqlCommand("select * from user where **employeeSSN = '" + employeeSSN_txt.Text + "'** and Password = '" + pass_txt.Text + "'", myConn);
MySqlDataReader myreader;
myConn.Open();
myreader = SelectCommand.ExecuteReader();
int count = 0;
while (myreader.Read())
{
count = count + 1;
}
if (count == 1)
{
Dashboard dashboard = new Dashboard();
dashboard.ShowDialog();
}
else if (count > 1)
{
XtraMessageBox.Show("Error logging in");
}
else
{
XtraMessageBox.Show("Incorrect Username and Password.Try Again");
}
}
catch (Exception ex)
{
XtraMessageBox.Show(ex.Message);
}
}
The part of code where I would like to use the Employee social security Number without having to input it manually.
private void simpleButton1_Click(object sender, EventArgs e)
{
string myConnection = "datasource = localhost;database = imprest system;port = 3306;username = root;password = ''";
MySqlConnection myConn = new MySqlConnection(myConnection);
MySqlCommand InsertCommand = new MySqlCommand("insert into expenseaccount where ExpenseType = '" + Expense_txt + "' and Amount = '" + Amount_txt + "' and **employeeSSN =** ", myConn);
MySqlDataReader myreader;
myConn.Open();
myreader = InsertCommand.ExecuteReader();
}
I'm basically new in coding, and I'm in uni, we have a small project to complete and I'm using OleDb to do it, as I have used it before, I'm trying to count the number of rows where a field is equal to a specific value, but I always get 0. To be more clear, I want statistics showing percentage of males/females who completed the survey(the program I'm making), currently I have 1 male and 2 females, so my string for all rows shows 3, which is correct, but when I want to count all the rows that contain females, it shows 0, so the total percentage is 0, and the textbox that's supposed to show the stat shows 0, here is the code:
private void Form2_Load(object sender, EventArgs e)
{
String connectionString;
connectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source='C:\Users\kubas\Desktop\MyProject\ProjectDB.accdb'";
using (OleDbConnection myConnection = new OleDbConnection(connectionString))
{
string Gender1 = "Female";
OleDbConnection con;
OleDbCommand cmd = new OleDbCommand();
OleDbCommand cmd1 = new OleDbCommand();
con = new OleDbConnection(connectionString);
con.Open();
cmd.CommandText = "SELECT Count(Gender) FROM Survey WHERE Gender = '" + Gender1 + "'";
cmd1.CommandText = "SELECT Count(Gender) FROM Survey";
cmd.Connection = con;
cmd1.Connection = con;
con.Close();
try
{
con.Open();
int total = (Int32)cmd.ExecuteScalar();
int total1 = (Int32)cmd1.ExecuteScalar();
int tot;
tot = total / total1 * 100;
string ttal = Convert.ToString(tot);
textBox1.Text = ttal;
con.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
if (con.State == ConnectionState.Open)
{
con.Close();
}
}
sorry if there is something you can't understand, English isn't my first language.
Maybe try this command query: "SELECT Count(Gender) FROM Survey WHERE Gender = \"" + Gender1 + "\"";
From what I can remember. access uses quotation marks for strings.
I am trying to Display a name in the textbox from the database if the ID entered by the user matches the record in the MS ACCESS DATABASE.
I'm getting the error Data type mismatch in criteria expression at the line int count = Convert.ToInt32(cmd.ExecuteScalar());
The following is my aspx.cs code-
protected void Button1_Click(object sender, EventArgs e)
{
clear();
idcheck();
DataTable dt = new DataTable();
OleDbConnection con = new OleDbConnection(#"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\dfg\fd\Visual Studio 2010\WebSites\WebSite21\App_Data\UPHealth.mdb");
con.Open();
str = "SELECT [DoctorName] FROM [DoctorInfo] WHERE DoctorID='" + TextBox1.Text.Trim() + "'";
OleDbCommand cmd = new OleDbCommand(str, con);
OleDbDataReader dr = cmd.ExecuteReader();
if (dr.Read())
{
TextBox2.Text = dr["DoctorID"].ToString();
dr.Close();
con.Close();
}
}
public void idcheck()
{
OleDbConnection con = new OleDbConnection(#"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\dfg\fd\Visual Studio 2010\WebSites\WebSite21\App_Data\UPHealth.mdb");
con.Open();
str = "SELECT count(DoctorName) FROM [DoctorInfo] WHERE DoctorID='" + TextBox1.Text.Trim() + "'";
OleDbCommand cmd = new OleDbCommand(str, con);
int count = Convert.ToInt32(cmd.ExecuteScalar());
if (count > 0)
{
Label21.Text = "Doctor Name";
}
else
{
Label21.Text = "Id Does not Exist";
}
}
void clear()
{
TextBox2.Text = "";
}
I guess that is because you as passing in an ID, which is usually a numeric value, as a text field:
DoctorID='" + TextBox1.Text.Trim() + "'
Which should be:
DoctorID=" + TextBox1.Text.Trim()
Another problem arises, since you are vulnerable to SQL injection. What if the text box contained 1; delete users? Then your entire users table would be empty. The lesson learned: use parameterized queries!
Then you can express the SQL as:
DoctorID= ?
And add the parameter to the request:
cmd.Parameters.AddWithValue("?", TextBox1.Text.Trim());
Can anybody tell me why my database isn't updating? Here's my code:
protected void editSection_selected(object sender, EventArgs e) {
int index = grdPhone.SelectedIndex;
GridViewRow row = grdPhone.Rows[index+1];
string values = ((DropDownList)sender).SelectedValue;
int tempVal = Convert.ToInt32(values);
int caseage = Convert.ToInt32(keyId);
int value = tempVal;
/*OleDbConnection con = new OleDbConnection(strConnstring);
//string query = "Update Categories set HRS_LEVEL_AMOUNT=" + tempVal + " where parent_id=65 and ID=" + caseage;
string query = "Delete HRS_LEVEL_AMOUNT from Categories where parent_id=65 and id=" + caseage;
OleDbCommand cmd = new OleDbCommand(query, con);
con.Open();
cmd.ExecuteNonQuery();
con.Dispose();
cmd.Dispose();
con.Close();
accPhoneNumbers.UpdateCommand = "Update Categories set HRS_LEVEL_AMOUNT=" + tempVal + " where parent_id=65 and ID=" + caseage;
*/
string str = "UPDATE Categories SET HRS_LEVEL_AMOUNT = ? WHERE ID=?";
using (OleDbConnection con = new OleDbConnection(strConnstring))
{
using (OleDbCommand cmd = new OleDbCommand(str, con))
{
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("HRS_LEVEL_AMOUNT", tempVal);
cmd.Parameters.AddWithValue("ID", caseage);
con.Open();
cmd.ExecuteNonQuery();
}
}
Label1.Text += " editSection Success! (B) " + tempVal;
}
The commented part is my first solution (including the accPhoneNumbers.UpdateCommand).
I really need your help guys.
I hope this can help you:
string str = "UPDATE Categories SET HRS_LEVEL_AMOUNT = #value1 WHERE ID=#value2";
using (OleDbConnection con = new OleDbConnection(strConnstring))
{
using (OleDbCommand cmd = new OleDbCommand(str, con))
{
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("#value1", tempVal);
cmd.Parameters.AddWithValue("#value2", caseage);
con.Open();
cmd.ExecuteNonQuery();
con.close();
}
}
For more information you can visit this video
I am trying to get next rows from the table of access database but I am getting last row all time.
Please guide me how to loop through all rows?
Here is the code:
protected void btn_clk(object sender, EventArgs e)
{
string constr = #"Provider=Microsoft.Jet.OLEDB.4.0; DataSource=C:\Users\Documents\databaseb.mdb";
string cmdstr1 = "select count(*) from table";
OleDbConnection con1 = new OleDbConnection(constr);
OleDbCommand com1 = new OleDbCommand(cmdstr1, con1);
con1.Open();
int count = (int) com1.ExecuteScalar();
int i = 2;
while(i<=count)
{
string cmdstr = "select * from table where id = " + i;
OleDbConnection con = new OleDbConnection(constr);
OleDbCommand com = new OleDbCommand(cmdstr, con);
con.Open();
OleDbDataReader reader = com.ExecuteReader();
reader.Read();
label1.Text = String.Format("{0}", reader[1]);
RadioButton1.Text = String.Format("{0}", reader[2]);
RadioButton2.Text = String.Format("{0}", reader[3]);
RadioButton3.Text = String.Format("{0}", reader[4]);
RadioButton4.Text = String.Format("{0}", reader[5]);
con.Close();
i++;
}
con1.Close();
}
=It`s must outside a button click:
string constr = #"Provider=Microsoft.Jet.OLEDB.4.0; Data Source=C:\Users\Documents\databaseb.mdb";
string cmdstr1 = "select count(*) from table";
OleDbConnection con1 = new OleDbConnection(constr);
OleDbCommand com1 = new OleDbCommand(cmdstr1, con1);
con1.Open();
int count = (int) com1.ExecuteScalar();
int i = 2;
con1.Close();
Its must inside button click. You must make i property of form
if(i<=count)
{
string cmdstr = "select * from table where id = " + i;
OleDbConnection con = new OleDbConnection(constr);
OleDbCommand com = new OleDbCommand(cmdstr, con);
con.Open();
OleDbDataReader reader = com.ExecuteReader();
reader.Read();
label1.Text = String.Format("{0}", reader[1]);
RadioButton1.Text = String.Format("{0}", reader[2]);
RadioButton2.Text = String.Format("{0}", reader[3]);
RadioButton3.Text = String.Format("{0}", reader[4]);
RadioButton4.Text = String.Format("{0}", reader[5]);
con.Close();
i++;
}
But i think it`s may rewrite to more beauty solve.
Sounds like you are after something like
private int _currentRecordId = -1;
...
string cmdStr = String.Format("SELECT * FROM Table WHERE id > {0} ORDER BY id LIMIT 1", _currentRecordId);
using (var con = new OleDbConnection(constr))
using (var com = new OleDbCommand(cmdStr, con))
{
con.Open();
using(var reader = com.ExecuteReader())
{
while (reader.Read())
{
_currentRecordId = reader.GetInt32(0); // whatever field the id column is
// populate fields
}
}
}
On first call this will retrieve the first record with an ID > -1. It then records whatever the ID is for this record so then on the next call it will take the first record greater than that e.g. if the first record is id 0 then the next record it will find is 1 and so on...
This only really works if you have sequential IDs of course.
Assuming that your table is not big (meaning it contains a manegeable number of records) you could try to load everything at the opening of your form and store that data in a datatable.
At this point the logic in your button should simply advance the pointer to the record to be displayed.
private DataTable data = null;
private int currentRecord = 0;
protected void form_load(object sender, EventArgs e)
{
using(OleDbConnection con1 = new OleDbConnection(constr))
using(OleDbCommand cmd = new OleDbCommand("select * from table", con1))
{
con1.Open();
using(OleDbDataAdapter da = new OleDbDataAdapter(cmd))
{
data = new DataTable();
da.Fill(data);
}
DisplayCurrentRecord();
}
}
private void DisplayCurrentRecord()
{
label1.Text = String.Format("{0}", data.Rows[currentRecord][1]);
RadioButton1.Text = String.Format("{0}", data.Rows[currentRecord][2]);
RadioButton2.Text = String.Format("{0}", data.Rows[currentRecord][3]);
RadioButton3.Text = String.Format("{0}", data.Rows[currentRecord][4]);
RadioButton4.Text = String.Format("{0}", data.Rows[currentRecord][5]);
}
protected void btn_clk(object sender, EventArgs e)
{
if(currentRecord >= data.Rows.Count - 1)
currentRecord = 0;
else
currentRecord++;
DisplayCurrentRecord();
}
Keep in mind that this is just an example. Robust checking should be applied to the rows (if they contains null values) and if there are rows at all in the returned table. Also, this is a poor man approach to the problem of DataBindings in WinForm, so perhaps you should look at some tutorials on this subject
Hope your table is not really named Table, that word is a reserved keyword for Access
simply remove the for loop to fetch record one by one
int lastFetchedRecordIndex=2;
protected void btn_clk(object sender, EventArgs e)
{
string constr = #"Provider=Microsoft.Jet.OLEDB.4.0; Data Source=C:\Users\Documents\databaseb.mdb";
string cmdstr1 = "select count(*) from table";
OleDbConnection con1 = new OleDbConnection(constr);
OleDbCommand com1 = new OleDbCommand(cmdstr1, con1);
con1.Open();
int count = (int) com1.ExecuteScalar();
string cmdstr = "select * from table where id = " + lastFetchedRecordIndex;
OleDbConnection con = new OleDbConnection(constr);
OleDbCommand com = new OleDbCommand(cmdstr, con);
con.Open();
OleDbDataReader reader = com.ExecuteReader();
reader.Read();
label1.Text = String.Format("{0}", reader[1]);
RadioButton1.Text = String.Format("{0}", reader[2]);
RadioButton2.Text = String.Format("{0}", reader[3]);
RadioButton3.Text = String.Format("{0}", reader[4]);
RadioButton4.Text = String.Format("{0}", reader[5]);
con.Close();
lastFetchedRecordIndex++;
con1.Close();
}