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 ;)
Related
I am trying to push data into a column where the name is a variable.
From the code below:
label1.Text is the dynamic column of the DB database (it is a string)
ComboBox1.Text is the data that I want to put into the dynamic column (column name = label1.Text)
connection.Open();
OleDBCommand command = new OleDbCommand();
command.Connection = connection;
command.ConnectionText = "update DB set column1='" + richTextBox1.Text + "', " + label1.Text + " = '" + comboBox1.Text + "' where ID=" + label2.Text;
command.ExecuteNonQuery();
connection.Close();
I have tried many different things such as moving the single quotes and double quote locations, add the & sign for the string concatenation. But all I have been able to do is push the label1.Text, ComboBox1.Text, and richTextBox1.Text all into column1...
This is only a small portion of my code, so please let me know if you have questions.
I've been trying to update the values from a sql database that's set as a data source in my windows form datagridview, but end up updating all rows instead.
I've been working on creating a basic task manager app for a development course that I'm enrolled in.
I'm having a hard time figuring out where the problem is located. I think that my code may not be properly set to the selected row?
I've supplied the code below, any and all help would be appreciated. If anyone need further clarification shoot me a message on the chat. throws a thumbs up
My Current Code:
private void UpdateBtn_Click(object sender, EventArgs e)
{
//Update button [almost done - data is not updating correctly]
string connectionString = "Data Source =ULTRA-COMPUTER; Initial Catalog =test; Persist Security Info =True; User ID = sa; Password = 12345";
SqlConnection con = new SqlConnection(connectionString);
string queryStatement = "SELECT * FROM testtask";
if (Task.Text != "" && Date.Text != "")
{
SqlCommand cmd = new SqlCommand(queryStatement, con);
DataTable task = new DataTable("testtask");
SqlDataAdapter ada = new SqlDataAdapter(cmd);
con.Open();
cmd.CommandText = "UPDATE [testtask] SET Task='" + Task.Text + "',Date='" + Date.Text + "' ";
cmd.Connection = con;
cmd.Parameters.AddWithValue("#Task", Task.Text);
cmd.Parameters.AddWithValue("#Date", Date.Text);
cmd.ExecuteNonQuery();
TaskData.DataSource = task;
MessageBox.Show("Update Inserted!");
ClearTxt();
}
else
{
MessageBox.Show("Please Enter A Task/DueDate To Update");
}
con.Close();
}
First add a hidden column for the primary key of your database table in datagridview. And now when you want to update the selected row that you have edited it use that primary key in where condition of your query.
cmd.CommandText = "UPDATE [testtask] SET Task='" + Task.Text + "',Date='" + Date.Text + "WHERE [TaskId]=#TaskId";
cmd.Parameters.AddWithValue("#TaskId", TaskIdFromDatagridview);
I think the problem is in this line
cmd.CommandText = "UPDATE [testtask] SET Task='" + Task.Text + "',Date='" + Date.Text + "' ";
You've not added the where clause that's why it'll update all rows in the table.
You must add a where clause.
For example you've taskid as primary key in this table and want to update a task with taskid 999 then your query must be
cmd.CommandText = "UPDATE [testtask] SET Task='" + Task.Text + "',Date='" + Date.Text + "' where taskid = 999 ";
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.
I'm working on a personal project where i want to get information of a customer from my database. However, i keep failing. The sql command i have:
"SELECT * FROM `customer` WHERE `ID` =#_ID AND `Naam` LIKE '" + tbKlantZoeken.Text + "'AND `E-mail` =#_EMAIL AND `Telefoon` =#_TEL"
The database connection is working, and another code related to the database is working aswell. So i guess it is my sql code? If not, Here's my code where i use it:
//Get info
db_connection();
MySqlCommand cmdZoeken = new MySqlCommand();
cmdZoeken.CommandText = "SELECT * FROM `customer` WHERE `ID` =#_ID AND `Naam` LIKE '" + tbKlantZoeken.Text + "'AND `E-mail` =#_EMAIL AND `Telefoon` =#_TEL";
cmdZoeken.Parameters.AddWithValue("#_ID", _ID);
cmdZoeken.Parameters.AddWithValue("#_EMAIL", _EMAIL);
cmdZoeken.Parameters.AddWithValue("#TEL", _TEL);
cmdZoeken.Connection = connect;
MySqlDataReader tbZoeken = cmdZoeken.ExecuteReader();
if (tbZoeken.Read())
{
connect.Close();
return true;
}
else
{
return false;
}
}
Other part:
//use code
db_connection();
string _ID = "ID";
string _EMAIL = "EMAIL";
string _TEL = "TEL";
try
{
bool Z = Klant_zoeken(_ID, _EMAIL, _TEL);
if (Z)
{
tbKResultaat.Text = _ID + " " + " " + _EMAIL + " " + _TEL;
}
}
catch
{
throw;
}
At this part, when it fails, the "throw" doesn't work aswell. It just crashes, but i think that is a question for another time...
Thanks in advance!
Check with this:- You have missing space between some words. Also add % mark for like according to your requirement. Unless use as Naam` = tbKlantZoeken.Text without like
"SELECT * FROM `customer` WHERE `ID` =#_ID AND `Naam` LIKE '" +
tbKlantZoeken.Text + "' AND `E-mail` =#_EMAIL AND `Telefoon` =#_TEL";
Try this
/Get info
db_connection();
MySqlCommand cmdZoeken = new MySqlCommand();
cmdZoeken.CommandText = "SELECT * FROM customer WHERE ID =#_ID AND Naam LIKE '" + tbKlantZoeken.Text + "%'AND E-mail =#_EMAIL AND Telefoon =#_TEL";
cmdZoeken.Parameters.AddWithValue("#_ID", _ID);
cmdZoeken.Parameters.AddWithValue("#_EMAIL", _EMAIL);
cmdZoeken.Parameters.AddWithValue("#TEL", _TEL);
cmdZoeken.Connection = connect;
MySqlDataReader tbZoeken = cmdZoeken.ExecuteReader();
if (tbZoeken.Read())
{
connect.Close();
return true;
}
else
{
return false;
}
}
You should remove single quates from Table_name and Column_name-
try select statement like this-
cmdZoeken.CommandText = "SELECT * FROM customer WHERE ID =#_ID AND Naam LIKE '%" + tbKlantZoeken.Text + "%'AND E-mail =#_EMAIL AND Telefoon =#_TEL";
When I click on this button, I face with this error:
executenonquery commandtext property has not been initialized
private void button_FirstStep_Click(object sender, EventArgs e)
{
SqlConnection Conn = new SqlConnection(Yahya.strcon);
Conn.Open();
int CurrentCount = Convert.ToInt32(label_CurrentCount.Text);
string strcom1 = "select * from vm1 where count = '" + (CurrentCount - 1) + "' and benchmarkid = '" + Structure.BenchmarkID + "' ";
SqlCommand cmd = new SqlCommand(strcom1, Conn);
SqlDataReader reader = cmd.ExecuteReader();
string strcom = "";
while (reader.Read())
{
if (reader["vmid"].ToString() != "")
{
string vmid = reader["vmid"].ToString();
strcom += "update vm1 set pmid = (select pmid from vm1 as VM2 where benchmarkid = '" + Structure.BenchmarkID + "' and vm2.count ='" + (CurrentCount - 1) + "' and vm2.vmid ='" + vmid + "' ) where count = '" + CurrentCount + "' and vmid = '" + vmid + "' and benchmarkid = '" + Structure.BenchmarkID + "' \n";
}
}//end of while
reader.Close();
cmd.CommandText = strcom;
cmd.ExecuteNonQuery();
}
Rene is quite right about his comment, looks like your reader.Read() returns false and that's why your code never goes into your while loop and your CommandText is assigned to "", that's why ExecuteNonQuery throws
ExecuteNonQuery: CommandText property has not been initialized
You can check your strcom is empty string or not to solve your problem but I see more wrong things in your code other than that..
Looks like your count column is numeric value but you supplied your CurrentCount - 1 as a character with single quotes. If it is not numeric, it should. Read: Bad habits to kick : choosing the wrong data type
Based on it's name, benchmarkid should(?) be numeric types as well.
You can solve this two problem with using parameterized queries because this kind of string concatenations are open for SQL Injection attacks.
Use using statement to dispose your connection, command and reader automatically instead of calling Close or Dispose methods manually.
Open your connection just before you execute your command.
You could solve this by simply debugging before asking.
The reason for this error is presumably that your first request returns zero results.
So reader.Read() is always false and strcom stays empty. You set an empty string as cmd.CommandText before the call to ExecuteNonQuery().
To solve this, simply check if the string is empty and execute the last query only if it is not empty:
...
reader.Close();
if (!string.IsNullOrEmpty(strcom))
{
cmd.CommandText = strcom;
cmd.ExecuteNonQuery();
}