public void Updatecottonpurchase(int slipno, int basicprice, int premium, int totalamountpaid, int weight, int totalamountbasic, int totalamountpremium, int yeildestimates, int farmercode)
{
SqlConnection sqlConn = new SqlConnection(#"Data Source=TANYA-PC;Initial Catalog=biore1;Integrated Security=True");
try
{
string sqlQuery = "UPDATE cottonpurchse SET slipno = '" + slipno + "' , basic price = '" + basicprice + "' , premium = '" + premium + "' , totalamountpaid = '" + totalamountpaid + "' , weight = '" + weight + "' , totalamountbasic = '" + totalamountbasic + "' , totalamountpremium = '" + totalamountpremium + "' , yeildestimated = '" + yeildestimates + "' WHERE farmercode = '" + farmercode + "'";
SqlCommand cmd = new SqlCommand(sqlQuery, sqlConn);
sqlConn.Open();
cmd.ExecuteNonQuery();
sqlConn.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
sqlConn.Close();
}
finally
{
sqlConn.Close();
}
}
this is what ive done now yet nothing happens! i want to beable to update the null values but nothing happens! please help
This SQL code:
UPDATE TABLE cottonpurchase SET slipno= WHERE farmercode=
Does nothing, you need to add parameters,
see: http://www.csharp-station.com/Tutorials/AdoDotNet/Lesson06.aspx
You need to change the code into:
....
string queryString =
"UPDATE TABLE cottonpurchase SET slipno=#slipno WHERE farmercode=#farmercode";
try
{
connection.Open();
SqlCommand command = new SqlCommand(queryString, connection);
//define parameters used in command object
SqlParameter param = new SqlParameter();
param.ParameterName = "#slipno";
param.Value = inputfromsomewhere;
SqlParameter param = new SqlParameter();
param.ParameterName = "#farmercode";
param.Value = inputfromsomewhereelse;
//add new parameter to command object
command.Parameters.Add(param);
int result = command.ExecuteNonQuery();
//if result = 1 the update is performed
}
......
You need to add or choose a column for use as the primary key. The primary key should uniquely identify a row, and is used to locate the row to update.
Related
I have a gridview that displays all the fields from my table.
My problem is that I need to update my SQL Server table when I click the save button (onclick) because I added a new field that generates a unique ID to every Item I have in my table. And It will add the generated id to the database table whenever I click the save button.
I have tried this
try
{
strSql = "UPDATE [dbo].[PRDetails] SET [buyerid] = '" + txtBuyerID.Text +
"' , [prno], [itemaname], [specification], [qty], [uomid], [expenseid],
[statusid], [userid], [inserteddate], [withquotation], [potempid] WHERE
idnum = '" + pridnum + "'";
SqlCommand UpdateCommand = new SqlCommand();
UpdateCommand = new SqlCommand(strSql, ConnString);
ConnString.Open();
UpdateCommand.ExecuteNonQuery();
ConnString.Close();
}
catch (Exception ex)
{
throw ex;
}
But I get an error
Here is my complete code:
public void SaveTogrdPOTemp()
{
SqlConnection ConnString = new SqlConnection(ConfigurationManager.ConnectionStrings["MUCS2.0ConnectionString"].ConnectionString);
string strSql = string.Empty;
pextid = "TPID";
using (SqlCommand cmd = new SqlCommand("SELECT * FROM GenIDGen WHERE extid = '" + pextid + "'"))
{
cmd.CommandType = System.Data.CommandType.Text;
cmd.Connection = ConnString;
ConnString.Open();
using (SqlDataReader sdr = cmd.ExecuteReader())
{
sdr.Read();
var extid = sdr["extid"].ToString().Trim();
var genID = sdr["generatedid"].ToString().Trim();
var gentr = sdr["generator"].ToString();
var potempoid = extid + genID;
ConnString.Close();
}
}
strSql = "UPDATE [dbo].[GenIDGen] SET [generator] = generator + 1
WHERE extid = '" + pextid + "' ";
SqlCommand UpdateCommand = new SqlCommand();
UpdateCommand = new SqlCommand(strSql, ConnString);
ConnString.Open();
UpdateCommand.ExecuteNonQuery();
ConnString.Close();
}
try
{
strSql = "UPDATE [dbo].[PRDetails] SET [buyerid] = '" + txtBuyerID.Text + "' WHERE idnum = '" + pridnum + "'";
SqlCommand UpdateCommand = new SqlCommand();
UpdateCommand = new SqlCommand(strSql, ConnString);
ConnString.Open();
UpdateCommand.ExecuteNonQuery();
ConnString.Close();
}
catch (Exception ex)
{
throw ex;
}
}
For the generating of ID and the updating of the gridview. Thank you!
I want to update my sql table. I was searching here and found solutions on how to go onto that problem. But sadly it just wont update the database. I have no clue what the problem is.
I checked to sql command a couple of times for writing mistakes but couldnt find any or fixed them but still sadly nothing. I suppose it's something within the try block but cant find it out.
This is my code:
string connetionString = null;
SqlConnection connection;
SqlCommand command;
string sql = null;
SqlDataReader dataReader;
connetionString = "Data Source=xxx\\xxx;Initial Catalog=xxx;User ID=xxx;Password=xxx";
sql = "UPDATE Employees SET LastName = '" + Lnamestring + "', FirstName = '" + Fnamestring + "', Title = '" + Titelstring + "', TitleOfCourtesy = '" + ToCstring + "', BirthDate = '" + Birthdatestring + "', HireDate = '" + Hiredatestring + "', Address = '" + Adressstring + "', City = '" + Citystring + "', Region = '" + Regionstring + "', PostalCode = '" + Postalstring + "', Country = '" + Countrystring + "', HomePhone = '" + Phonestring + "', Extension = '" + Extensionsstring + "', Notes = '" + Notesstring + "', ReportsTo = '" + ReportTostring + "' WHERE EmployeeID = '" + IDstring + "'; ";
connection = new SqlConnection(connetionString);
try
{
connection.Open();
command = new SqlCommand(sql, connection);
SqlDataAdapter sqlDataAdap = new SqlDataAdapter(command);
command.Dispose();
connection.Close();
MessageBox.Show("workd ! ");
}
catch (Exception ex)
{
MessageBox.Show("Can not open connection ! ");
}
I hope someone can help me find my mistake.
EDIT: when i try it out it seems to work as the windows pops up with "workd" but the database is unchanged.
As MichaĆ Turczyn wrote in his answer, you have some problems with your code.
I agree with everything he wrote, but I thought you might benefit from seeing how your code should look like - so here you go:
var connetionString = "Data Source=EVOPC18\\PMSMART;Initial Catalog=NORTHWND;User ID=test;Password=test";
var sql = "UPDATE Employees SET LastName = #LastName, FirstName = #FirstName, Title = #Title ... ";// repeat for all variables
try
{
using(var connection = new SqlConnection(connetionString))
{
using(var command = new SqlCommand(sql, connection))
{
command.Parameters.Add("#LastName", SqlDbType.NVarChar).Value = Lnamestring;
command.Parameters.Add("#FirstName", SqlDbType.NVarChar).Value = Fnamestring;
command.Parameters.Add("#Title", SqlDbType.NVarChar).Value = Titelstring;
// repeat for all variables....
connection.Open();
command.ExecuteNonQuery();
}
}
}
catch (Exception e)
{
MessageBox.Show($"Failed to update. Error message: {e.Message}");
}
Few issues with your code:
1) Use using, when working with IDisposable objects, in your case connection and command.
2) As suggested in comments, use SqlCommandParameters instead of concatenating strings for security reasons (google "preventing from SQL injections")
3) You don't execute your query! How you want it to make an impact if you don't do it? There's, for example, method like ExecuteNonQuery in SqlCommand class.
string connetionString = null;
SqlConnection connection;
SqlCommand command;
string sql = null;
SqlDataReader dataReader;
connetionString = "Data Source=EVOPC18\\PMSMART;Initial Catalog=NORTHWND;User ID=test;Password=test";
sql = "UPDATE Employees SET LastName = '" + Lnamestring + "', FirstName = '" + Fnamestring + "', Title = '" + Titelstring + "', TitleOfCourtesy = '" + ToCstring + "', BirthDate = '" + Birthdatestring + "', HireDate = '" + Hiredatestring + "', Address = '" + Adressstring + "', City = '" + Citystring + "', Region = '" + Regionstring + "', PostalCode = '" + Postalstring + "', Country = '" + Countrystring + "', HomePhone = '" + Phonestring + "', Extension = '" + Extensionsstring + "', Notes = '" + Notesstring + "', ReportsTo = '" + ReportTostring + "' WHERE EmployeeID = '" + IDstring + "'; ";
connection = new SqlConnection(connetionString);
try
{
connection.Open();
command = new SqlCommand(sql, connection);
SqlDataAdapter sqlDataAdap = new SqlDataAdapter(command);
command.ExecuteNonQuery();
command.Dispose();
connection.Close();
MessageBox.Show("workd ! ");
}
catch (Exception ex)
{
MessageBox.Show("Can not open connection ! ");
}
Don't forget to execute the command
Try to get the stacktrace or error message from Exception as much as possible. For example: MessageBox.Show($"Can not open connection ! {e.GetBaseException().Message}, {e.StackTrace}");
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandText = "update CarTb1 set ( #RegNo , #MOdel , #Price , #Available where #Brand);";
cmd.CommandType = System.Data.CommandType.Text;
Da = new SqlDataAdapter("Select * From CarTb1", con);
Da.Fill(Dt);
cmd.Parameters.AddWithValue("#RegNo", txtRegnumber.Text);
cmd.Parameters.AddWithValue("#Brand", combBrand.Text);
cmd.Parameters.AddWithValue("#Model", txtModel.Text);
cmd.Parameters.AddWithValue("#Price", txtPrice.Text);
cmd.Parameters.AddWithValue("#Color", txtColor.Text);
cmd.Parameters.AddWithValue("#Available", combAvailable.Text);
con.Open();
cmd.ExecuteNonQuery();
MessageBox.Show("Record Edited Successfally");
con.Close();
ClearData();
Please use the ExecuteNonQuery() instead of SqlDataAdapter:
connection.Open();
command = new SqlCommand(sql, connection);
command.ExecuteNonQuery();
command.Dispose();
connection.Close();
MessageBox.Show("workd ! ");
var conString = ConfigurationManager.ConnectionStrings["CONSTRING"].ConnectionString;
SqlConnection con = new SqlConnection(conString);
string uname = Session["un"].ToString();
Label sid = (Label)DetailsView1.Rows[1].Cells[1].Controls[0].FindControl("lblsid");
TextBox nam = (TextBox)DetailsView1.Rows[2].Cells[1].Controls[0].FindControl("lblname");
TextBox lnam = (TextBox)DetailsView1.Rows[3].Cells[1].Controls[0].FindControl("lbllname");
TextBox cont = (TextBox)DetailsView1.Rows[4].Cells[1].Controls[0].FindControl("lblcon");
TextBox ei = (TextBox)DetailsView1.Rows[5].Cells[1].Controls[0].FindControl("lblei");
TextBox add = (TextBox)DetailsView1.Rows[6].Cells[1].Controls[0].FindControl("lbladd");
TextBox cit = (TextBox)DetailsView1.Rows[7].Cells[1].Controls[0].FindControl("lblcit");
DropDownList typ = (DropDownList)DetailsView1.Rows[8].Cells[1].Controls[0].FindControl("lbltyp");
cmd.Connection = con;
cmd.CommandText = "update seller set fname ='" + nam.Text + "', lname ='" + lnam.Text + "', contact ='" + cont.Text + "', address ='" + add.Text + "', city ='" + cit.Text + "', type='" + typ.SelectedValue + "' where sid=" + sid.Text + "";
cmd.Connection.Open();
cmd.ExecuteNonQuery();
DetailsView1.ChangeMode(DetailsViewMode.ReadOnly);
BindData();
I know this way is to find the control but I dont know how to pass Sid value in the query. can some one help? working on C#
Use parameters. Below I am showing you how to do so for first name. You can do the rest like this.
SqlCommand cmd = new SqlCommand(
"update seller set fname = #firstName", con);
// 2. define parameters used in command object
SqlParameter param = new SqlParameter();
param.ParameterName = "#firstName";
param.Value = nam;
// 3. add new parameter to command object
cmd.Parameters.Add(param);
This is my screen shot
Bellow Is My Code For Update Button Click Event!
{
try
{
con = new SqlConnection(cs.ConDB);
con.Open();
string cb = "Update tblFees set Salutation= '" + cmbSalutation.Text + "' , Name= '" + tbName.Text + "',Sex = '" + cmbSex.Text + "', Date ='" + Date.Text + "',Fees_Amount='" + cmbFeesAmount.Text + "',Fees_Status='" + radioButton1.Checked + "'";
cmd = new SqlCommand(cb);
cmd.Connection = con;
cmd.ExecuteReader();
con.Close();
MessageBox.Show("Successfully updated", "Record", MessageBoxButtons.OK, MessageBoxIcon.Information);
btnUpdate.Enabled = false;
btnSave.Enabled = true;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
try
{
con = new SqlConnection(cs.ConDB);
con.Open();
cmd = new SqlCommand("SELECT * From tblFees", con);
SqlDataAdapter myDA = new SqlDataAdapter(cmd);
DataSet myDataSet = new DataSet();
myDA.Fill(myDataSet, "tblFees");
dataGridView1.DataSource = myDataSet.Tables["tblFees"].DefaultView;
con.Close();
}catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);}`
Please Solve my problem i am new in the programming world
any help would be greatly appreciated
you should specify the rows using where condition
For example you can modify your query something like the following. I assume cboUser is a combo box there you can select particular user, so that the data updated for that selected user only.
SqlConnection con = new SqlConnection();
con.Open();
string cb = "Update [tblFees] set Salutation=#Salutation, Name=#Name,Sex =#Sex where tblFeesPK=#pk'";
SqlCommand cmd = new SqlCommand(cb, con);
cmd.Parameters.AddWithValue("#Salutation", cmbSalutation.Text);
cmd.Parameters.AddWithValue("#Name", tbName.Text);
cmd.Parameters.AddWithValue("#Sex", cmbSex.Text);
cmd.Parameters.AddWithValue("#pk", cboUser.SelectedValue);
cmd.ExecuteNonQuery();
If you want to update details based on name means: you can give name
in where condition. but it's not a proper way. so use primary
key(since name may have duplicate values)
You need to change the statement as:
string cb = "Update tblFees set Salutation= '" + cmbSalutation.Text + "' , Name= '" + tbName.Text + "',Sex = '" + cmbSex.Text + "', Date ='" + Date.Text + "',Fees_Amount='" + cmbFeesAmount.Text + "',Fees_Status='" + radioButton1.Checked + "' where Name= '" + tbName.Text + "'";
You need to add where Name= '" + tbName.Text + "';
Now it will update those rows where Name matches
Also as un-lucky said u should use parameterized queries
This probably a simple solution, but I've got a deadline to catch and I don't know the exact problem here.
So here's the deal, I'm trying to update my table using this piece of code:
private void btn_opslaan_Click(object sender, EventArgs e)
{
string opleidingsid = "Select OpleidingsID From opleidingen Where Opleidingsnaam = '" + cb_opleiding.Text + "'";
MySqlCommand cmdid = new MySqlCommand(opleidingsid, dbconnect.connection);
dbconnect.OpenConnection();
MySqlDataReader reader = cmdid.ExecuteReader();
reader.Read();
int oplid = (int)reader.GetValue(0);
cmdid.Dispose();
reader.Close();
sql = "UPDATE leerlingen SET Naam = '_naam', Adres = '_adres', Woonplaats = '_woonplaats', Postcode = '_postcode', Email = '_email', Telefoonnummer = '_telefoonnummer', Klas = '_klas', Ovnummer = '_ovnummer', OpleidingsID = '_opleidingsid', Startdatum = '_startdatum', Einddatum = '_einddatum' WHERE LeerlingID = '_leerlingid'";
// sql = "UPDATE leerlingen set Naam = '" + txt_naam.Text + "', Adres = '" + txt_adres.Text + "', Woonplaats = '" + txt_woonplaats.Text + "', Postcode = '" + txt_postcode.Text + "', Email = '" + txt_email.Text + "', Telefoonnummer = '" + txt_telefoonnumer.Text + "', Klas = '" + txt_klas.Text + "', Ovnummer = '" + txt_ovnummer.Text + "', OpleidingsID = '" + oplID + "', Startdatum = '"+mc_startdatum.SelectionStart.Date.ToString()+"', Einddatum = '"+ mc_einddatum.SelectionStart.Date.ToString() +"' WHERE LeerlingID = '" + Int32.Parse(lbl_leerlingid.Text) + "'";
MySqlCommand cmd = new MySqlCommand(sql, dbconnect.connection);
cmd.Parameters.AddWithValue("_naam", txt_naam.Text);
cmd.Parameters.AddWithValue("_adres", txt_adres.Text);
cmd.Parameters.AddWithValue("_woonplaats", txt_woonplaats.Text);
cmd.Parameters.AddWithValue("_postcode", txt_postcode.Text);
cmd.Parameters.AddWithValue("_email", txt_email.Text);
cmd.Parameters.AddWithValue("_telefoonnummer", txt_telefoonnumer.Text);
cmd.Parameters.AddWithValue("_klas", txt_klas.Text);
cmd.Parameters.AddWithValue("_ovnummer", txt_ovnummer.Text);
cmd.Parameters.AddWithValue("_opleidingsid", oplid);
cmd.Parameters.AddWithValue("_startdatum", mc_startdatum.SelectionStart.Date.ToString());
cmd.Parameters.AddWithValue("_einddatum", mc_einddatum.SelectionStart.Date.ToString());
cmd.Parameters.AddWithValue("_leerlingid", int.Parse(lbl_leerlingid.Text));
try
{
cmd.ExecuteNonQuery();
MessageBox.Show("opslaan gelukt");
}
catch (Exception error)
{
MessageBox.Show(error.ToString());
throw;
}
dbconnect.CloseConnection();
this.Close();
}
I've already tried without the single quotes, it would give me the error that colomn '_leerlingid' does not exist, but that is the parameter...
Now, I dont get any errors, but it wouldn't update my database.
Any help please
P.S. Ignore the sql injection please, before this , i didn't knew better before I found out about parameters.
Try replacing your parameters with the # symbol and remove the single quotes, like this:
SQL = "UPDATE leerlingen SET Naam = #naam, Adres = #adres";
cmd.Parameters.AddWithValue("#naam", txt_naam.Text);
cmd.Parameters.AddWithValue("#adres", txt_adres.Text);
I think what you did wrong is you mustn't initialize your MySqlCommand like that. It must be like this..
MySqlCommand cmd;
cmd = dbconnect.createCommand();
cmd.CommandText = "UPDATE tableName SET firstname=#firstname, lastname=#lastname where id=#id";
cmd.Parameters.AddWithValue("#id", idTxt.Text);
cmd.Parameters.AddWithValue("#firstname", fName.Text);
cmd.Parameters.AddWithValue("#lastname", lName.Text);
cmd.ExecuteNonQuery();
when I creating a new data in c#, I make it like this ..
//values
String a = "COL1ROW1", b = "COL1ROW2";
//this is the code for mysql
String query = "Insert Into tableName(Column1, Column2)values('" + a + "','" + b + "')";
//conn is your mysqlconnection
MySqlCommand cmd = new MySqlCommand(query, conn);
//then execute it
cmd.ExecuteNonQuery();