Click here to Skip to main content
15,915,336 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Hi,
Please help me with this, I have already closed the connection but still, I get the same error.

What I have tried:

if (Validation())
            {
                
                // Insert Logic
                con.Open();

                
                if (ifComponentsExist(con, textBox1.Text))
                {
                    sqlquery = @"UPDATE [Components]SET [APartNo] = '" + textBox8.Text + "',[Availability] = '" + textBox3.Text + "',[Quantity] = '" + textBox4.Text + "',[Date] ='" + dateTimePicker1.Value.ToString() + "',[Amount] = '" + textBox7.Text + "',[CompDiscription] = '" + textBox2.Text + "',[CompanyName] = '" + textBox5.Text + "',[Stored On] = '" + comboBox1.Text + "',[Stored No] = '" + textBox9.Text + "' WHERE [CompPartNo] = '" + textBox1.Text + "'";
                }
                else
                {
                    sqlquery = @"INSERT INTO [IMS].[dbo].[Components]([APartNo],[CompPartNo],[CompDiscription],[Availability],[Quantity],[CompanyName],[Amount],[Date],[Stored On])
                    VALUES
                          ('" + textBox8.Text + "','" + textBox1.Text + "','" + textBox2.Text + "','" + textBox3.Text + "','" + textBox4.Text + "','" + textBox5.Text + "','" + textBox7.Text + "','" + dateTimePicker1.Value.ToString() + "','" + comboBox1.Text + "','" + textBox9.Text + "')";
                }

                SqlCommand cmd2 = new SqlCommand(sqlquery, con);
                cmd2.ExecuteNonQuery();

                con.Close();
Posted
Updated 11-Nov-20 19:53pm

Don't do it like that! Never concatenate strings to build a SQL command. It leaves you wide open to accidental or deliberate SQL Injection attack which can destroy your entire database. Always use Parameterized queries instead.

When you concatenate strings, you cause problems because SQL receives commands like:
SQL
SELECT * FROM MyTable WHERE StreetAddress = 'Baker's Wood'
The quote the user added terminates the string as far as SQL is concerned and you get problems. But it could be worse. If I come along and type this instead: "x';DROP TABLE MyTable;--" Then SQL receives a very different command:
SQL
SELECT * FROM MyTable WHERE StreetAddress = 'x';DROP TABLE MyTable;--'
Which SQL sees as three separate commands:
SQL
SELECT * FROM MyTable WHERE StreetAddress = 'x';
A perfectly valid SELECT
SQL
DROP TABLE MyTable;
A perfectly valid "delete the table" command
SQL
--'
And everything else is a comment.
So it does: selects any matching rows, deletes the table from the DB, and ignores anything else.

So ALWAYS use parameterized queries! Or be prepared to restore your DB from backup frequently. You do take backups regularly, don't you?

BTW: Do yourself a favour, and stop using Visual Studio default names for everything - you may remember that "TextBox8" is the mobile number today, but when you have to modify it in three weeks time, will you then? Use descriptive names - "tbMobileNo" for example - and your code becomes easier to read, more self documenting, easier to maintain - and surprisingly quicker to code because Intellisense can get to to "tbMobile" in three keystrokes, where "TextBox8" takes thinking about and 8 keystrokes...

[edit]
And another thing: it's a bad practice to "recycle" a single global Connection object - it leads to some really nasty problems later if you aren't very careful.
Create your SqlConnection object inside a using block when you need it, Open it, use it, and let the block Dispose it when you are finished:
C#
using (SqlConnection con = new SqlConnection(strConnect))
    {
    con.Open();
    using (SqlCommand cmd = new SqlCommand("INSERT INTO myTable (myColumn1, myColumn2) VALUES (@C1, @C2)", con))
        {
        cmd.Parameters.AddWithValue("@C1", myValueForColumn1);
        cmd.Parameters.AddWithValue("@C2", myValueForColumn2);
        cmd.ExecuteNonQuery();
        }
    }

[/edit]
 
Share this answer
 
v2
Comments
ishuishika 12-Nov-20 2:37am    
But the same code is working in other forms why not in this?
Please help me to sort out this one. From the next project, I'll learn how to use parameters and start...
Thank you so much that You made me understand the use of parameters.
OriginalGriff 12-Nov-20 3:27am    
No, change your existing code to use parameters. If you don't, then your whole DB is at risk - this is not a "it might happen", this is a real problem.

I can't see your "other forms" so I have no idea what they are doing.

Seriously, it'll take you half an hour tops to convert all your existing code to use the proper things - so do it and all your problems disappear!
If you don't, then there is a good chance that they will come back anyway once you fix this!
There might be some error. Debugging should tell the flow of execution.

To be on safer side, follow the best practice by:
Option 1: Put the ado.net code in a try-finally[^]
Quote:
By using a finally block, you can clean up any resources that are allocated in a try block, and you can run code even if an exception occurs in the try block.

C#
try
{
  //
}
finally
{
   con.close();
}

Option 2: Use using statement[^]
Quote:
Provides a convenient syntax that ensures the correct use of IDisposable objects

C#
using(var con = new SqlConnection(connectionString))
{
  // code
}
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900