Click here to Skip to main content
15,920,438 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
An exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll but was not handled in user code
i am stuck here, con.Open();

What I have tried:

C#


SqlConnection con = new SqlConnection("Data Source=DESKTOP-72CIIS5;Initial Catalog=user_desk;User ID=sa;Password=***********");
SqlCommand cmd = new SqlCommand("insert into usertable values ('" + textBox1.Text + "','" + textBox2.Text + "','" + textBox3.Text + "','" + textBox4.Text + "',)", con);
con.Open();
Posted
Updated 7-Nov-18 21:18pm
v2
Comments
F-ES Sitecore 6-Nov-18 7:31am    
Your connection string is wrong. If you look at the actual exception message it will give you hint about what is wrong.

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?

And if you fix that, the syntax problem with your SQL will be very, very obvious:
C#
using (SqlCommand cmd = new SqlCommand("INSERT INTO usertable VALUES (@P1, @P2, @P3, @P4, @p5,)", con)
   {
   ...

In addition:
1) Always list the columns you wish to insert into. That way, changes to your table (and IDENTITY columns) don;t mess up your data.
2) 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...
 
Share this answer
 
Comments
Richard Deeming 6-Nov-18 9:01am    
Also, connecting as sa is particularly dangerous. 🤦‍♂️
ali walo 7-Nov-18 4:16am    
so how I fix it plz tell me?
OriginalGriff 7-Nov-18 4:28am    
Use parameterised queries! Google will show you how ...
OriginalGriff 7-Nov-18 4:30am    
And check your connection string (they shouldn't be hard coded either). This may help:
https://www.codeproject.com/Tips/1198443/Simple-SQL-Connection-String-Creation
It seems you are opening connection in wrong place.

steps to follow

1. Create Sql Connection
2. Open connection
3. assign connection to command.

while in your case your are swaping 2 and 3.

More over use parameters instead of building query

here is example for you

C#
using (connection = new SqlConnection(connectionString))
{
  connection.Open();
  var command = new SqlCommand();
  command.CommandText = @"
     INSERT INTO [dbo].[Product]
           ([ProductId]
           ,[Name]
           ,[Description])           
     VALUES
          (@Pid,
           @Name,
           @Desc)";
 command.Connection = connection;
 command.Parameters.Add(new SqlParameter("@Pid", SqlDbType.VarChar, 100)).Value = product.ProductId;
 command.Parameters.Add(new SqlParameter("@Name", SqlDbType.VarChar, 100)).Value = product.Name;
 command.Parameters.Add(new SqlParameter("@Desc", SqlDbType.VarChar, 255)).Value = product.Description;                
 command.ExecuteNonQuery();
}
 
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