I am working on a C# project. I have created a dataset by use of sql server and I tried to show the data in DataGridView table. Then I added a button to change the selected data. when I use English language for editing the data, it works perfectly. But when I change the language, question mark is shown.
to edit the data I use the following commands.
sqlStr = "Update Employee Set FirstName = '" + FirstName.Text + "' Where ID = '" + ID.Text + "'";
cmd.CommandText = sqlStr;
cmd.Connection = connect;
cmd.ExecuteNonQuery();
any help is appreciated.
thanks
Change:
sqlStr = "Update Employee Set FirstName = '" + FirstName.Text + "' Where ID = '" + ID.Text + "'";
to:
sqlStr = "Update Employee Set FirstName = N'" + FirstName.Text + "' Where ID = N'" + ID.Text + "'";
Without the N at the start, you are using varchar rather than nvarchar. Which basically means that Persian characters will show as ?
I think you should use SqlParameters like this:
sqlStr = "Update Employee Set FirstName = #FirstName Where ID = #Id";
SqlParameter param = new SqlParameter();
param.ParameterName = "#FirstName";
param.Value = FirstName.Text;
cmd.Parameters.Add(param);
param = new SqlParameter();
param.ParameterName = "#Id";
param.Value = ID.Text;
cmd.Parameters.Add(param);
This, also, avoid sql injection.
Related
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);
There is a textbox called tbTodo, which gets information from the database:
SELECT `todo` FROM `user` WHERE `username` LIKE '" + _naam + "'";
which works. The problem now is, i have no idea how to update the todo list in the database: how to send the textbox value and overwrite the one from the database. Code i have so far (which could be totally wrong):
db_connection();
MySqlCommand cmdRead = new MySqlCommand();
cmdRead.CommandText = "SELECT `todo` FROM `user` WHERE `username` LIKE '" + _naam + "'";
cmdRead.Connection = connect;
MySqlDataReader tdOphalen = cmdRead.ExecuteReader();
if (tdOphalen.Read())
{
tbTodo.Text = tdOphalen.GetString(0);
connect.Close();
return true;
}
else
{
connect.Close();
return false;
}
}
syntax of UPDATE command is
UPDATE table_name
SET column1=value1,column2=value2,...
WHERE some_column=some_value;
In your case it would be something like
"UPDATE `user` set `todo` = '" + tbTodo.Text + "' FROM `user` WHERE `username` LIKE '" + _naam + "'";
It should be good for a first try and learn how update values on a database.
Next steps is learn how to use prepared statement ;)
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();
can any one please help. I have a table with three fields a field Amount, LatestUpdate and Note, I want to update the three fields using parameters to avoid any sql injection. I need help on writing them the correct way using parameter.Add().
here is the code.
com.CommandText = "update tblStore set Amount=Amount + #amount, LatestUpdate=#latestUpdate, Notes = convert(nvarchar(4000),#notes) + '. " + item.notes + "' WHERE ID=1";
com.Parameters.Add("#amount", item.amount.ToString());
com.Parameters.Add("#latestUpdate", item.fuelingDate.ToString());
com.Parameters.Add("#notes", item.notes.ToString());
You're nearly there.. You want something like
com.Parameters.Add("#amount", SqlDbType.Int).Value = item.amount;;
com.Parameters.Add("#latestUpdate", SqlDbType.DateTime).Value = item.fuelingDate;;
com.Parameters.Add("#notes", SqlDbType.NVarChar).Value = item.notes;
Don't forget to include using System.Data;
You need to add parameters along with the SqlDBType. Do not use the AddWithValue method because several article mention that it is not very safe. I would use the following:
com.CommandText = "update tblStore set Amount=Amount + #amount, LatestUpdate=#latestUpdate, Notes = #notes WHERE ID=1";
SqlParameter parameter = new SqlParameter("#amount", System.Data.SqlDbType.Int);
parameter.Value = item.amount;
com.Parameters.Add(parameter);
parameter = new SqlParameter("#latestUpdate", System.Data.SqlDbType.DateTime);
parameter.Value = item.fuelingDate;
com.Parameters.Add(parameter);
parameter = new SqlParameter("#notes", System.Data.SqlDbType.NVarChar);
parameter.Value = item.notes;
com.Parameters.Add(parameter);
--UPDATE--
To update the notes instead of overwriting, just change the commandText:
com.CommandText = "update tblStore set Amount=Amount + #amount, LatestUpdate=#latestUpdate, Notes = Notes + #notes WHERE ID=1";
this is the final code that works, I am sharing it in case anyone else needs it. Thank you all for your help.
com.CommandText = "update tblStore set Amount=Amount + #amount, LatestUpdate=#latestUpdate, Notes = convert(nvarchar(4000),Notes) + '.' + #notes WHERE ID=1";
com.Parameters.Add("#amount", SqlDbType.Int).Value = item.amount; ;
com.Parameters.Add("#latestUpdate", SqlDbType.DateTime).Value = item.fuelingDate; ;
com.Parameters.Add("#notes", SqlDbType.NVarChar).Value = item.notes;
are you looking for this ?
com.CommandText = "update tblStore set Amount=Amount + #amount,
LatestUpdate=#latestUpdate, Notes = convert(nvarchar(4000),#notes) + '. " +
item.notes + "' WHERE ID=1";
com.Parameters.AddWithValue("#amount", item.amount.ToString());
com.Parameters.AddWithValue("#latestUpdate", item.fuelingDate.ToString());
com.Parameters.AddWithValue("#notes", item.notes.ToString());
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.