-2

This is what I want to use;

string insertQuery = @"insert into userinfo (UserName, FirstName, LastName, 
                      E-mail, Password,  Country) 
                      values ( '" + uname + "', '" + fname + 
                      "','" + lname + "', '" + email + "')";

where every one of the variables in between the + are string variables with values in them. but when I run this command, I get some incorrect syntax error.

This is the new error i get;

errorSystem.Data.SqlClient.SqlException (0x80131904): String or binary data would be truncated. The statement has been terminated. at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action1 wrapCloseInAction) at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action1 wrapCloseInAction) at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose) at System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady) at System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, String resetOptionsString) at System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean async, Int32 timeout, Task& task, Boolean asyncWrite, SqlDataReader ds) at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, TaskCompletionSource1 completion, Int32 timeout, Task& task, Boolean asyncWrite) at System.Data.SqlClient.SqlCommand.InternalExecuteNonQuery(TaskCompletionSource1 completion, String methodName, Boolean sendToPipe, Int32 timeout, Boolean asyncWrite) at System.Data.SqlClient.SqlCommand.ExecuteNonQuery() at Registration.RegistrationPage.Button1_Click1(Object sender, EventArgs e) in c:\Users\kristhnen.jagambrum\Documents\Visual Studio 2012\Projects\Registration\Registration\RegistrationPage.aspx.cs:line 50 ClientConnectionId:6d959e49-5b62-43be-b202-76f7eb1fbd2c

MatthewMartin
  • 32,326
  • 33
  • 105
  • 164
  • 9
    [SQL Injection alert](http://msdn.microsoft.com/en-us/library/ms161953%28v=sql.105%29.aspx) - you should ***NEVER*** concatenate together your SQL statements like you're proposing; ***ALWAYS*** use **parametrized queries** instead to avoid SQL injection!! – marc_s Nov 28 '14 at 17:02
  • 1
    You're listing 6 columns to insert data into, but only 4 values. And yes, please look into using `Parameters` to prevent SQL injection. – Drew Kennedy Nov 28 '14 at 17:03
  • 2
    In addition to what @marc_s said, the column `E-mail` needs to be escaped since this is an expression, `E` minus `mail`. Try `"E-mail"` or `[E-mail]`, but yes, **do not concatenate strings to form sql!** – Lasse V. Karlsen Nov 28 '14 at 17:03
  • Heed the above warning first & foremost, but in the short term, you can debug the code & see what value is assigned to `insertQuery` – markpsmith Nov 28 '14 at 17:04
  • `I get some incorrect syntax error` is not very useful information, at all. Why not copy and paste the error text into your post? – Paul Sasik Nov 28 '14 at 17:05
  • What about Password and Country column where is their corresponding values ?? – Pravin Nov 28 '14 at 17:06

3 Answers3

5

It's very good that you asked - the code that you show is a perfect illustration of two security issues in a single line:

  • The table structure is an illustration of what lets hackers steal user passwords.
  • The C# code is what makes SQL injection attacks possible.

Fixing the first problem is hard: you need to learn about password hashing and how to store user info in DB. Here is a Q&A that will help: Best way to store passwords in DB

The second problem is easier - all you need is replacing the injected values with parameter names, and then adding the values for each parameter name:

... // Create SQL command, then set its text
command.CommandTest = @"INSERT INTO userinfo (
    UserName, FirstName, LastName, E-mail, Password_hash, Password_salt, Country
) VALUES ( @uname, @fname, @lname, @email, @pwd_hash, @pwd_salt, @country)";
// Bind the parameters
command.Parameters.Add(new SqlParameter("@uname", uname));
command.Parameters.Add(new SqlParameter("@fname", fname));
... // ...and so on
command.ExecuteNonQuery();
Community
  • 1
  • 1
Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
1

The answer is you don't, because it is a bad idea. You should be using SQlCommand instead

Check This out,and there are plenty of examples of how to use it. Appending variables in the way you doing is considered to be the mistake number 3 in the list of 25 most dangerous programming mistakes.

Sleiman Jneidi
  • 22,907
  • 14
  • 56
  • 77
1

Try something like this, and not use direct parameter in sql command

public const string InsertStmtUsersTable = "insert into userinfo (UserName, FirstName, LastName, 
                      [E-mail], Password,  Country) values (@UserName, @FirstName, @LastName, 
                      @[E-mail], @Password,  @Country) "
    using(SqlConnection conn = new SqlConnection(connString))
    {
        conn.Open();

        using (SqlCommand command = new SqlCommand(InsertStmtUsersTable, conn))
        {
           command.CommandType = CommandType.Text;

           command.Parameters.Add(new SqlParameter("username", userNameString));
           command.Parameters.Add(new SqlParameter("FirstName", FirstNameString));
           // Rest of your Parameters here

           command.ExecuteNonQuery();
        }
    }
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
HaveNoDisplayName
  • 8,291
  • 106
  • 37
  • 47
  • 1
    1. `SqlCommand` is disposable too, wrap it in a `using`. 2. Rather than `Parameters.Add(new SqlParameter(...))` you can just use `Parameters.AddWithValue()`. – Jeroen Mostert Nov 28 '14 at 17:13
  • @JeroenMostert: you should check out [Can we stop using AddWithValue() already?](http://blogs.msmvps.com/jcoehoorn/blog/2014/05/12/can-we-stop-using-addwithvalue-already/) and be careful using `.AddWithValue()` - it can lead to unexpected and surprising results... – marc_s Nov 28 '14 at 17:15
  • @JeroenMostert: there are multiple way to do everything, this is just the sample code, so that OP got some idea, how to do this – HaveNoDisplayName Nov 28 '14 at 17:15
  • @marc_s: thanks for that one, I had it tickling in the back of my mind but couldn't find the page. Note that in this case, the `new SqlParameter()` omits the type, so it's certainly no *better*. – Jeroen Mostert Nov 28 '14 at 17:19
  • 1
    Thanks @marc_s, to notice typo, Using of using – HaveNoDisplayName Nov 28 '14 at 17:21