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.
Related
What i intend to do is to insert the value into SQL database table. Firstly, let me explain the flow. I generate dynamic textboxes on the Form. Next, while inserting all the values from other textboxes and comboboxes i do no have any problem. But to get all the values entered manually from dynamically created textboxes was a challenge for me. Which i managed to fix it using the following code.
foreach (TextBox textbox in this.panel1.Controls.OfType<TextBox>())
{
string message_0 = "";
message_0 = textbox.Text.ToString();
}
But when i insert the values into the database using the insert query i face a problem into database. The value gets inserted with the duplication of other columns too if i place the for loops curly braces after the sql commands.
foreach (TextBox textbox in this.panel1.Controls.OfType<TextBox>())
{
string message_0 = "";
message_0 = textbox.Text.ToString();
SqlCommand cmd = con.CreateCommand();
cmd.CommandType = CommandType.Text;
string a = "insert into new_product (name, description, image, fk_type, date, reference, field_value) values ('" + textBox3.Text + "', '" + richTextBox1.Text + "' ,#images ,'" + comboBox1.SelectedValue.ToString() + "', '" + dateTimePicker1.Value.ToString("dd-mm-yy") + "','" + textBox1.Text + "', '" + message_0 + "') ";
cmd.CommandText = a;
cmd.Parameters.Add(new SqlParameter("#images", images));
cmd.ExecuteNonQuery();
table_update();
}
Is it normal in this case or am i doing anything wrong here. Any help would be appreciated guys. Thank you.
enter image description here
This question already has answers here:
SQL update statement in C#
(10 answers)
Closed 5 years ago.
enter image description here
I am trying to update data in a SQL Server table. I get a message that data is saved, after a query execution.
But when I check in that table, I find that the data is not saved. Is anything wrong in my query?
I am using SQL Server 2008 and C# for coding.
SqlCommand cmd1 = new SqlCommand("UPDATE Inward_Rpt SET Date='" + date + "',Cashier_Name='" + cashier_name + "',Supplier_Code='" + sup_code + "',Supplier_Name='" + name + "',Payment_Mode ='" + p_method + "',Total_Bill='" + tot_bill + "',Total_Paid='" + tot_paid + "',Previous_Due = '" + total_due + "',Current_Due ='" + c_due + "',Remark ='" + remark + "'WHERE Supplier_Name='" + name + "'", con);
cmd1.ExecuteNonQuery();
MessageBox.Show("Data Saved..");
I think I found your error. Your WHERE clause is using the same name that you are updating the Supplier Name to. Assuming this is a new name, you will never find the record you want to update. The below code is cleaner, not prone to injection issues, and it should work the way you want.
Note that you will have to provide a new variable to cater to the name / sup_name situation.
SqlCommand cmd1 = new SqlCommand();
cmd1.Connection = con;
cmd1.CommandText = #"
UPDATE Inward_Rpt
SET Date = #date
, Cashier_Name = #cashier_name
, Supplier_Code = #sup_code
, Supplier_Name = #sup_name
, Payment_Mode = #p_method
, Total_Bill = #tot_bill
, Total_Paid = #tot_paid
, Previous_Due #total_due
, Current_Due = #c_due
, Remark = #remark
WHERE Supplier_Name = #name";
cmd1.Parameters.AddWithValue("#date", date);
cmd1.Parameters.AddWithValue("#cashier_name", cashier_name);
cmd1.Parameters.AddWithValue("#sup_code", sup_code);
cmd1.Parameters.AddWithValue("#sup_name", sup_name);
cmd1.Parameters.AddWithValue("#p_method", p_method);
cmd1.Parameters.AddWithValue("#tot_bill", tot_bill_name);
cmd1.Parameters.AddWithValue("#tot_paid", tot_paid);
cmd1.Parameters.AddWithValue("#total_due", total_due);
cmd1.Parameters.AddWithValue("#c_due", c_due);
cmd1.Parameters.AddWithValue("#remark", remark);
cmd1.Parameters.AddWithValue("#name", name);
cmd1.ExecuteNonQuery();
MessageBox.Show("Data Saved..");
Is the All the Fields are String Datatype in your Database Table? Check the Datatypes Because u give Single Quotes for all Data. If the Table Datatype is Number Remove the Single Quotes.
SqlCommand cmd1 = new SqlCommand("UPDATE Inward_Rpt SET Date='" + date + "',Cashier_Name='" + cashier_name + "',Supplier_Code=" + sup_code + ",Supplier_Name='" + name + "',Payment_Mode ='" + p_method + "',Total_Bill='" + tot_bill + "',Total_Paid='" + tot_paid + "',Previous_Due = '" + total_due + "',Current_Due ='" + c_due + "',Remark ='" + remark + "'WHERE Supplier_Name='" + name + "'", con);
I do want to pass StudName contents to my declared variable. i tried " +a.ToString+" But still i got errors
string a;
connection.Close();
connection.Open();
String strSQL = "select *from Students where StudName = '" +a.ToString() + "' and StudNum = '" + studentNumber;
OleDbCommand command = new OleDbCommand(strSQL);
StudNum = '" + studentNumber
The Database column for studentNumber is numeric but you're half treating it as alphanumeric.
Solution
StudNum = " + studentNumber
You need to use Parameterised commands to protect against an SQL Injection attack. This will also solve issues such as variables containing apostrophes and etc that would also cause your sql to fail.
I'm a student programmer and I'm writing this software for a small school, it's my first program, the code below is giving me the error
syntax error in insert into statement
I know the connection string is not the problem because I use it for inserting into two other tables with the same insert into format.
I am using an access database.
The offending code is
connection.Open();
OleDbCommand command = new OleDbCommand();
command.Connection = connection;
command.CommandText = "insert into studentBillRecords (StudentName, Department, Level, AccomodationStatus, SemesterBill, PreviousBalance, TotalBill) values ('"+ txtSRstudentName.Text + "', '" + cmbSRDepartment.Text + "', '" + cmbSRLevel.Text + "', '" + cmbSRAccomodationStatus.Text + "', '" + txtSRSemesterBill.Text + "', '" + txtSRPreviousBalance.Text + "', '" + txtSRTotalBill.Text + "')";
MessageBox.Show(command.CommandText);
command.ExecuteNonQuery();
connection.Close();
This same code with different table names, column names and input works with another table in the same database but won't work with this one.
Level is a reserved keyword in access.
Also use Parameters instead of concatinating string. Try this code out, it makes it safer and easier to read:
Note: I changed the name of the column Level to StudentLevel which, I assume, doesn't exist yet in your table.
try
{
using (OleDbConnection connection = new OleDbConnection("my connection string"))
{
//Open connection
connection.Open();
//Create new command
OleDbCommand cmd = new OleDbCommand();
cmd.Connection = connection;
//Create command text
cmd.CommandText =
"INSERT INTO studentBillRecords " +
"(StudentName, Department, StudentLevel, AccomodationStatus, SemesterBill, PreviousBalance, TotalBill) VALUES " +
"(#StudentName, #Department, #StudentLevel, #AccomodationStatus, #SemesterBill, #PreviousBalance, #TotalBill)";
// Add names paremeters
cmd.Parameters.AddRange(new OleDbParameter[]
{
new OleDbParameter("#StudentName", txtSRstudentName.Text),
new OleDbParameter("#Department", cmbSRDepartment.Text),
new OleDbParameter("#StudentLevel", cmbSRLevel.Text),
new OleDbParameter("#AccomodationStatus", cmbSRAccomodationStatus.Text),
new OleDbParameter("#SemesterBill", txtSRSemesterBill.Text),
new OleDbParameter("#PreviousBalance", txtSRPreviousBalance.Text),
new OleDbParameter("#TotalBill", txtSRTotalBill.Text)
});
//Execute Query
cmd.ExecuteNonQuery();
//No need to close because we are using "using"
}
}
catch (OleDbException ex)
{
//If an exception occurs let's print it out to console
Console.WriteLine("ERROR: " + ex.ToString());
throw;
}
For information on how to change the column name read this:
https://msdn.microsoft.com/en-us/library/bb177883(v=office.12).aspx
"Level" is a keyword in MS Access, may be that is why this issue occurs try quoting it like [Level]
List Of MS Access Keywords
I would like to save record from assigning a value to textbox.text from a variable then will be saved the record from textbox to database. I have tried it but a garbage value always saved in the database instead of the value I assign to the textbox.
here are my line of code:
string r = "returned";
comboBox2 = r;
SqlConnection MySqlConnection;
MySqlConnection = new SqlConnection("Data Source=**************;Initial Catalog=lights and sounds;User ID=*****;Password=********;");
MySqlConnection.Open();
SqlDataReader dr;
SqlCommand command = new SqlCommand("Update reservation_inventory Set status= '" + comboBox2 + "' WHERE id = '" + textBox1.Text + "' ", MySqlConnection);
dr = command.ExecuteReader();
dr.Close();
this is the garbage value that saved in the database:
System.Windows.Forms.TextBox, Text: returned
your help will be highly appreciated. thank you
I think comboBox2 is a Textbox control. Then you need to set .Text property of your control.
In your case you should use:
string r = "returned";
comboBox2.Text = r;
and same change in your SqlCommand
SqlCommand command = new SqlCommand("Update reservation_inventory Set status= '" + comboBox2.Text + "' WHERE id = '" + textBox1.Text + "' ", MySqlConnection);
Please try to use
comboBox2.Text
instead of using comboBox2. I suppose that comboBox2 is a TextBox. So you need to read it's Text attribute.
It's reasonable that you took
System.Windows.Forms.TextBox
because when you try to concatenate the following strings:
"Update reservation_inventory Set status= '" +
comboBox2 +
"' WHERE id = '" + textBox1.Text + "' "
the ToString() method of comboBox2 is called. Hence you get it's type name.
use comboBox2.Text (or comboBox2.content - depends on what kind of Control) to access the text insde the Control
if you use just comboBox2 in a string variable c# will implicitly call the .toString()-Method on the Control wich returns the Name of the Control.
in this case this is "System.Windows.Forms.TextBox"