update mysql database (DDT-groupname) - c#

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 { }
}

Related

Connection was not closed. Connection's current State was open

I'm currently finishing my payroll system with ms access database used to connect with my program. CRUD is one of our main requirements to finish this project but ADD button said that my connection was not closed. Connection's current State was open.
private void btnAddDB_Click(object sender, EventArgs e)
{
try
{
Connection.Open();
OleDbCommand command1 = new OleDbCommand();
OleDbCommand command2 = new OleDbCommand();
OleDbCommand command3 = new OleDbCommand();
command1.Connection = Connection;
command2.Connection = Connection;
command3.Connection = Connection;
command1.CommandText = "Select* from employeeinfo where Employee ID = '" + txtEID.Text + "'";
OleDbDataReader reader1 = command1.ExecuteReader();
command2.CommandText = "Select* from employeeinfo where Email Address = '" + txtEA.Text + "'";
OleDbDataReader reader2 = command2.ExecuteReader();
command3.CommandText = "Select* from employeeinfo where Contact Number = '" + txtCN.Text + "'";
OleDbDataReader reader3 = command3.ExecuteReader();
string conn1, conn2, conn3;
while (reader1.Read())
{
con1.Text = reader1["Employee ID"].ToString();
}
while (reader2.Read())
{
con2.Text = reader2["Email Address"].ToString();
}
while (reader3.Read())
{
con3.Text = reader3["Contact Number"].ToString();
}
conn1 = con1.Text;
if (conn1 != con1.Text)
{
conn2 = con2.Text;
if (conn2 != con2.Text)
{
conn3 = con3.Text;
if (conn3 != con3.Text)
{
OleDbCommand command = new OleDbCommand();
command.Connection = Connection;
command.CommandText = "INSERT INTO employeeinfo ([Employee ID], [Employee Name], [Department], [First Name], [Middle Name, [Surname], [Address], [Contact Number], [Email Address], [Salary]) values(#empid, #empname, #dep, #fname, #mname, #sname, #address, #connum, #emadd, #sal)";
command.Parameters.AddWithValue("#empid", txtEID.Text);
command.Parameters.AddWithValue("#empname", txtEN.Text);
command.Parameters.AddWithValue("#dep", txtDep.Text);
command.Parameters.AddWithValue("#fname", txtFN.Text);
command.Parameters.AddWithValue("#mname", txtMN.Text);
command.Parameters.AddWithValue("#sname", txtSN.Text);
command.Parameters.AddWithValue("#address", txtAdd.Text);
command.Parameters.AddWithValue("#connum", txtCN.Text);
command.Parameters.AddWithValue("#emadd", txtEA.Text);
command.Parameters.AddWithValue("#sal", textBox2.Text);
command.ExecuteNonQuery();
MessageBox.Show("Employee Information Created");
}
else if (conn3 == txtCN.Text)
{
MessageBox.Show("Contact Number Already exist");
con3.Text = "";
}
}
else if (conn2 == txtEA.Text)
{
MessageBox.Show("Email Address Already exist");
con2.Text = "";
}
}
else if (conn1 == txtEID.Text)
{
MessageBox.Show("Email ID Already exist");
con1.Text = "";
}
Connection.Close();
}
catch (Exception ex)
{
MessageBox.Show("error" + ex);
}
}

How to open next form base on select query base on flag

I am creating one application my requirement is what when column name Status is N in Registration table, then current form should hide and Login form should be open.
If Status is not N then its should be open Registration_Form. I'm trying but it's causing
Error creating window handle
on the rf.Show() call.
on insert button code
string status = "Y";
//Random random = new Random();
//int randomNumber = random.Next(0, 100);
string random1 = System.Web.Security.Membership.GeneratePassword(10, 0);
string concate = textBox1.Text + "-" + textBox2.Text + "-" + textBox3.Text.Substring(textBox3.Text.Length - 4) + "-" + random1;
string connectionString = null;
connectionString = ConfigurationManager.ConnectionStrings["AccessConnectionString"].ConnectionString;
con.ConnectionString = connectionString;
string SqlString = "Insert Into Registration (Name,Last_Name,Contact_No,Address,Insert_Date,Registration_key,Status) Values (?,?,?,?,?,?,?)";
//using (OleDbCommand cmd = new OleDbCommand(SqlString, con))
//{
OleDbCommand cmd = new OleDbCommand(SqlString, con);
con.Open();
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("#Name", textBox1.Text);
cmd.Parameters.AddWithValue("#Last_Name", textBox2.Text);
cmd.Parameters.AddWithValue("#Contact_No", textBox3.Text);
cmd.Parameters.AddWithValue("#Address", textBox4.Text);
cmd.Parameters.AddWithValue("#Insert_Date", textBox5.Text);
cmd.Parameters.AddWithValue("#Registration_key", concate);
cmd.Parameters.AddWithValue("#Status", status);
//}
int n = cmd.ExecuteNonQuery();
con.Close();
if (n > 0)
{
MessageBox.Show("Data Inserted Successfully,NOW PLEASE ACTIVATE APPLICATION PUTTING ACTIVATE KEY ", "Data Inserted ", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
on update button code --
string Status = "N";
string connectionString = null;
connectionString = ConfigurationManager.ConnectionStrings["AccessConnectionString"].ConnectionString;
con.ConnectionString = connectionString;
string recover = "SELECT Registration_key from Registration where Registration_key='" + textBox6.Text + "'";
OleDbCommand cmd = new OleDbCommand(recover, con);
con.Open();
OleDbDataReader reader = cmd.ExecuteReader();
if (reader.Read())
{
textBox6.Text = reader["Registration_key"].ToString();
if (con.State == ConnectionState.Open)
{
con.Close();
}
string cmd1 = "update Registration set Status=#Status where Registration_key=#Registration_key";
cmd = new OleDbCommand(cmd1, con);
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("#Status", Status);
cmd.Parameters.AddWithValue("#Registration_key", textBox6.Text);
con.Open();
int n2 = cmd.ExecuteNonQuery();
con.Close();
this.Hide();
Login_Page lp = new Login_Page();
lp.Show();
}
else
{
MessageBox.Show("Invalid Activated Key", "Invalid", MessageBoxButtons.OK, MessageBoxIcon.Stop);
}
con.Close();
on load event--
string connectionString = null;
connectionString = ConfigurationManager.ConnectionStrings["AccessConnectionString"].ConnectionString;
con.ConnectionString = connectionString;
string Comparing="N";
string query = "select Status from Registration where Status='N'";
con.Open();
OleDbCommand cmd = new OleDbCommand(query, con);
string compare = Convert.ToString(cmd.ExecuteScalar());
con.Close();
if (compare == Comparing)
{
this.Hide();
Login_Page lp = new Login_Page();
lp.Show();
}
else if (compare != Comparing)
{
Registration_Form rf = new Registration_Form();
rf.Show();
}
i got a solution i remove e
lse if (compare != Comparing)
{
Registration_Form rf = new Registration_Form();
rf.Show();
}
this and instead that normal use else condition
connectionString = ConfigurationManager.ConnectionStrings["AccessConnectionString"].ConnectionString;
con.ConnectionString = connectionString;
string Comparing="N";
string query = "select Status from Registration where Status='N'";
con.Open();
OleDbCommand cmd = new OleDbCommand(query, con);
string compare = Convert.ToString(cmd.ExecuteScalar());
con.Close();
if (compare == Comparing)
{
this.Hide();
Login_Page lp = new Login_Page();
lp.Show();
}
else
{
MessageBox.Show("Pls Register yourself");
}
this code giving me what requirement i want

SQL visual studio command

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

MS Access database not updating

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

Updating multiple tables using SqlDataAdapter

I've been trawling through pages and pages on the internet for days now trying different approaches and I'm still not sure how I should be doing this.
On my third InsertCommand, I'd like to reference a column on the other 2 tables.
// Populate a DataSet from multiple Tables... Works fine
sqlDA = new SqlDataAdapter();
sqlDA.SelectCommand = new SqlCommand("SELECT * FROM hardware", sqlConn);
sqlDA.Fill(ds, "Hardware");
sqlDA.SelectCommand.CommandText = "SELECT * FROM software";
sqlDA.Fill(ds, "Software");
sqlDA.SelectCommand.CommandText = "SELECT * FROM join_hardware_software";
sqlDA.Fill(ds, "HS Join");
// After DataSet has been changed, perform an Insert on relevant tables...
updatedDs = ds.GetChanges();
SqlCommand DAInsertCommand = new SqlCommand();
DAInsertCommand.CommandText = "INSERT INTO hardware (host, model, serial) VALUES (#host, #model, #serial)";
DAInsertCommand.Parameters.AddWithValue("#host", null).SourceColumn = "host";
DAInsertCommand.Parameters.AddWithValue("#model", null).SourceColumn = "model";
DAInsertCommand.Parameters.AddWithValue("#serial", null).SourceColumn = "serial";
sqlDA.InsertCommand = DAInsertCommand;
sqlDA.Update(updatedDs, "Hardware"); // Works Fine
DAInsertCommand.Parameters.Clear(); // Clear parameters set above
DAInsertCommand.CommandText = "INSERT INTO software (description) VALUES (#software)";
DAInsertCommand.Parameters.AddWithValue("#software", null).SourceColumn = "description";
sqlDA.InsertCommand = DAInsertCommand;
sqlDA.Update(updatedDs, "Software"); // Works Fine
DAInsertCommand.Parameters.Clear(); // Clear parameters set above
DAInsertCommand.CommandText = "INSERT INTO join_hardware_software (hardware_id, software_id) VALUES (#hardware_id, #software_id)";
// *****
DAInsertCommand.Parameters.AddWithValue("#hardware_id", null).SourceColumn = "?"; // I want to set this to be set to my 'hardware' table to the 'id' column.
DAInsertCommand.Parameters.AddWithValue("#software_id", null).SourceColumn = "?"; // I want to set this to be set to my 'software' table to the 'id' column.
// *****
sqlDA.InsertCommand = DAInsertCommand;
sqlDA.Update(updatedDs, "HS Join");
Could somebody please tell me where I am going wrong and how I could potentially overcome this? Many thanks! :)
With regards to your comments this seems to be one of those occasions where if you and I were sat next to each other we'd get this sorted but it's a bit tricky.
This is code I've used when working with SqlConnection and SqlCommand. There might be stuff here that would help you.
public static void RunSqlCommandText(string connectionString, string commandText) {
SqlConnection conn = new SqlConnection(connectionString);
SqlCommand comm = conn.CreateCommand();
try {
comm.CommandType = CommandType.Text;
comm.CommandText = commandText;
comm.Connection = conn;
conn.Open();
comm.ExecuteNonQuery();
} catch (Exception ex) {
System.Diagnostics.EventLog el = new System.Diagnostics.EventLog();
el.Source = "data access class";
el.WriteEntry(ex.Message + ex.StackTrace + " SQL '" + commandText + "'");
} finally {
conn.Close();
comm.Dispose();
}
}
public static int RunSqlAndReturnId(string connectionString, string commandText) {
SqlConnection conn = new SqlConnection(connectionString);
SqlCommand comm = conn.CreateCommand();
int id = -1;
try {
comm.CommandType = CommandType.Text;
comm.CommandText = commandText;
comm.Connection = conn;
conn.Open();
var returnvalue = comm.ExecuteScalar();
if (returnvalue != null) {
id = (int)returnvalue;
}
} catch (Exception ex) {
System.Diagnostics.EventLog el = new System.Diagnostics.EventLog();
el.Source = "data access class";
el.WriteEntry(ex.Message + ex.StackTrace + " SQL '" + commandText + "'");
} finally {
conn.Close();
comm.Dispose();
}
return id;
}

Categories

Resources