i am trying to update a mysql database through visual studio
String str = "server=localhost;database=population;username=root;password=hello;Convert Zero Datetime=true;";
MySqlConnection con = new MySqlConnection(str);
string col1 = col.Text;
string newval1=newval.Text;
string val1=val.Text;
try
{
con.Open();
string cmdstr="update npanxx set \""+col1+"\" = \""+newval1+"\" where NPA_NXX=\""+val1+"\"";
MySqlCommand cmd = new MySqlCommand(cmdstr, con);
cmd.ExecuteNonQuery();
con.Close();
}
catch(Exception err)
{
MessageBox.Show(err.ToString());
}
when I run this and click the button it says I have a syntax error but I have not be able to find it. Can anyone point it out to me
You don't need quotes around the column col1:
String str = "server=localhost;database=population;username=root;password=hello;Convert Zero Datetime=true;";
MySqlConnection con = new MySqlConnection(str);
string col1 = col.Text;
string newval1=newval.Text;
string val1=val.Text;
try
{
con.Open();
string cmdstr="update npanxx set "+col1+" = \""+newval1+"\" where NPA_NXX=\""+val1+"\"";
MySqlCommand cmd = new MySqlCommand(cmdstr, con);
cmd.ExecuteNonQuery();
con.Close();
}
catch(Exception err)
{
MessageBox.Show(err.ToString());
}
I would do it this way:
String str = "server=localhost;database=population;username=root;password=hello;Convert Zero Datetime=true;";
MySqlConnection con = new MySqlConnection(str);
string col1 = col.Text;
string newval1=newval.Text;
string val1=val.Text;
try
{
con.Open();
MySqlCommand cmd = new MySqlCommand("Update npanxx set '"+ col1 +"'='" + newval1 + "' WHERE NPA_NXX= '" + val1 + "'", con);
MySqlCommand cmd = new MySqlCommand(cmdstr, con);
cmd.ExecuteNonQuery();
con.Close();
}
catch(Exception err)
{
MessageBox.Show(err.ToString());
}
Related
Below is the description.
**Table**
Pid memberId name date taxAmount
1 04 Sam 1/1/16 £10
2 07 John 1/4/16 £12
3 04 Sam 2/5/16 £17
4 06 Paul 3/5/16 £10
5 04 Sam 5/6/16 £10
Say I want to retrieve Sam's or any other persons' transactions from the database in Asp.net. Please what is the sql statement?
Sorry guys,please below is my complete code. I tried it but it didn't work.I would be glad is someone can help.
{
OleDbConnection conn = new OleDbConnection(System.Configuration.ConfigurationManager.ConnectionStrings["Myconnection"].ConnectionString);
try
{
conn.Open();
string checkuser = "select count(*) from RegisteredMember where firstName='" + txtFirstName.Text + "'";
OleDbCommand cmd = new OleDbCommand(checkuser, conn);
int temp = Convert.ToInt32(cmd.ExecuteScalar().ToString());
conn.Close();
if (temp == 1)
{
conn.Open();
string checkUserIDQuery = "select memberID from RegisteredMember where firstName='" + txtFirstName.Text + "'";
OleDbCommand IDcmd = new OleDbCommand(checkUserIDQuery, conn);
string memberID = IDcmd.ExecuteScalar().ToString();
if (memberID == txtUserID.Text)
{
Session["New"] = txtUserID.Text;
OleDbCommand Plotcmd = new OleDbCommand();
cmd.Connection = conn;
string query = "select * from payment where memberID= "+ txtMemberID.Text + "'";
cmd.CommandText = query;
OleDbDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
Chart1.Series["Tax History"].Points.AddXY(reader["date"].ToString(), reader["taxAmount"].ToString());
}
}
string connString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=E:\Shamila Stuff\campus\semester 2\comp 1551-Application and Web Developement\asp\fwp\fwp\FwpDatabase.accdb"; // put your path
myConnection = new OleDbConnection(connString);
string query = "select * from payment where memberID= '"+ txtMemberID.Text + "'";
if (myConnection == null)
myConnection = GetConnection();
OleDbCommand myCommand = new OleDbCommand(myQuery, myConnection);
try
{
myConnection.Open();
myCommand.ExecuteNonQuery();
}
catch (Exception ex)
{
Console.Write(ex);
}
finally
{
myConnection.Close();
}
try
{
myConnection.Open();
OleDbDataReader reader = myCommand.ExecuteReader();
if (reader.HasRows == true)
{
reader.Read();
string myQuery1 = Chart1.Series["Tax History"].Points.AddXY(reader["date"].ToString(), reader["taxAmount"].ToString());
myCommand = new OleDbCommand(myQuery1, myConnection);
myCommand.ExecuteNonQuery();
reply = true;
}
else
{
reply = false;
}
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
finally
{
myConnection.Close();
}
Put your connections string for the database in the mentioned place.
I am trying to retrieve data from a Database and show them on a form; but my code isn't working... I've got no errors, and logically it seems to work (to me) so I cannot figure out where I have gone wrong. That's where I need your help!
private void tableListBox_SelectedIndexChanged(object sender, EventArgs e)
{
string constring = #"Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\IncomerDefault.mdf;Integrated Security=True;Connect Timeout=30";
string Query = "SELECT * FROM [Table] WHERE Default_Name = '" + tableListBox.SelectedValue + "'";
SqlConnection con = new SqlConnection(constring);
SqlCommand cmd = new SqlCommand(Query, con);
SqlDataReader Reader;
try
{
con.Open();
Reader = cmd.ExecuteReader();
while (Reader.Read())
{
textBox1.Text = Reader.GetValue(2).ToString();
comboBox1.Text = Reader.GetValue(3).ToString();
comboBox3.Text = Reader.GetValue(4).ToString();
textBox2.Text = Reader.GetValue(6).ToString();
comboBox2.Text = Reader.GetValue(7).ToString();
comboBox4.Text = Reader.GetValue(8).ToString();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
con.Close();
}
The 'tableListBox' is populated with all the values in column 'Default_Name'. I want it so that when the 'Default_Name' is selected from the list box it shows the values, in textboxes and comboboxes, that correspond with that row in the Database.
Any and all help would be appreciated. Thanks.
I'm going to start by changing your design a bit and suggest that perhaps you look at using a datatable and then just retrieving the rows from the datatable.
private void tableListBox_SelectedIndexChanged(object sender, EventArgs e)
{
private DataTable dataTable;
string constring = #"Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\IncomerDefault.mdf;Integrated Security=True;Connect Timeout=30";
string Query = "SELECT * FROM [Table] WHERE Default_Name = '" + tableListBox.SelectedValue + "'";
SqlConnection con = new SqlConnection(constring);
SqlCommand cmd = new SqlCommand(Query, con);
try
{
con.Open();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dataTable);
foreach(DataRow row in dataTable.Rows)
{
textBox1.Text = row[2].ToString();
comboBox1.Text = row[3].ToString();
comboBox3.Text = row[4].ToString();
textBox2.Text = row[6].ToString();
comboBox2.Text = row[7].ToString();
comboBox4.Text = row[8].ToString();
}
da.Dispose();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
con.Close();
}
I generally find that DataTables are more reliable than looping through the actual reader. Ofcourse this assumes that there is data being returned. Also try changing your select statement to this
string Query = "SELECT * FROM [Table]"
If that works, then the problem could be
There is no default name of the specified value or
tableListBox.SelectedValue is not returning any value, in which case, have a look at your listbox selected value
Thanks to Takarii for helping. I figured out who to make it work.
private void tableListBox_SelectedValueChanged(object sender, EventArgs e)
{
string constring = #"Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\IncomerDefault.mdf;Integrated Security=True;Connect Timeout=30";
string Query = "SELECT * FROM [Table] WHERE ID = '" + tableListBox.SelectedIndex.ToString() + "'";
SqlConnection con = new SqlConnection(constring);
SqlCommand cmd = new SqlCommand(Query, con);
SqlDataReader Reader;
try
{
con.Open();
Reader = cmd.ExecuteReader();
while (Reader.Read())
{
textBox1.Text = Reader.GetValue(2).ToString();
comboBox1.Text = Reader.GetValue(3).ToString();
comboBox3.Text = Reader.GetValue(4).ToString();
textBox2.Text = Reader.GetValue(6).ToString();
comboBox2.Text = Reader.GetValue(7).ToString();
comboBox4.Text = Reader.GetValue(8).ToString();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
con.Close();
}
First I changed the void to 'SelectedValueChanged' and then I changed the 'WHERE' in the connection Query to the Row Index associated with the selected Value.
Thanks for everyone's help!
MySqlConnection conn = new MySqlConnection("server=localhost;uid=root;" + "pwd=password;database=ddt_data");
conn.Open();
string command = "Update `fixture` SET `referee`=#referee, `ScoreA`=#ScoreA, `ScoreB`=#ScoreB, `Winner`=#Winner WHERE idfixture=" + Request.QueryString["idfixture"];
MySqlCommand update = new MySqlCommand(command, conn);
update.Parameters.AddWithValue("#referee", this.txtRef.Text);
update.Parameters.AddWithValue("#scorea", this.txtScoreA.Text);
update.Parameters.AddWithValue("#scoreb", this.txtScoreB.Text);
update.Parameters.AddWithValue("#winner", this.txtWinner.Text);
update.ExecuteNonQuery(); // use this if you don't need the DataReader
conn.Close();
conn.Dispose();
MySqlConnection conn = new MySqlConnection("server=localhost;uid=root;" + "pwd=password;database=ddt_data");
conn.Open();
try
{
string command = "Update fixture SET referee =#referee," + "ScoreA = #ScoreA, ScoreB = #ScoreB, Winner = #Winner " + "WHERE idfixture= " + Request.QueryString["idfixture"];
MySqlCommand update = new MySqlCommand(command, conn);
update.Parameters.AddWithValue("#referee", this.txtRef.Text);
update.Parameters.AddWithValue("#scorea", this.txtScoreA.Text);
update.Parameters.AddWithValue("#scoreb", this.txtScoreB.Text);
update.Parameters.AddWithValue("#winner", this.txtWinner.Text);
update.ExecuteNonQuery(); // use this if you don't need the DataReader
conn.Close();
conn.Dispose();
}
catch { }
}
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
private void fillcode()
{
try
{
SqlConnection con = new SqlConnection("Data Source=ANISH;Initial Catalog=HM;Integrated Security=True");
con.Open();
string s = "select max(CustomerId) as Id from CustomerDetails";
SqlCommand cmd = new SqlCommand(s, con);
SqlDataReader dr = cmd.ExecuteReader();
dr.Read();
int i = Convert.ToInt16(dr["Id"].ToString());
sid.Text = (i + 1).ToString();
con.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
I am using this code, but there is a problem if there is no data in my table it will not accept.
So I want to use if no data is present it should take CustomerId as 1
It will be NULL of there are no rows so you can:
"select isnull(max(CustomerId), 1) as Id from CustomerDetails"
You should also look at ExecuteScalar which is designed for a singe result.
Try like this
private void fillcode()
{
try
{
SqlConnection con = new SqlConnection("Data Source=ANISH;Initial Catalog=HM;Integrated Security=True");
con.Open();
string s = "select max(CustomerId) as Id from CustomerDetails";
SqlCommand cmd = new SqlCommand(s, con);
SqlDataReader dr = cmd.ExecuteReader();
if(dr.Read())
{
int i = Convert.ToInt16(dr["Id"].ToString());
sid.Text = (i + 1).ToString();
}
else
{
sid.Text = "1"
}
con.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}