Inserting alphanumeric into SQL db?

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Paul73
    New Member
    • Sep 2007
    • 13

    Inserting alphanumeric into SQL db?

    Hi everyone,

    I'm hoping someone can help me. I've created a windows app that inserts data into a sql database.

    The data comes from textboxes. This is a simple app that will only be used by me on a local computer so I'm not worried about sql injections.

    My problem is this...if I enter a job id that contains all numbers (ie. 12345) into textBox1 everything works fine and the database inserts the new record. But if I enter a job id that is alphanumeric (ie. 12345b) I receive a syntax error.

    In my database the field is set as varchar(MAX) so I don't understand why this is throwing an error. If I manually insert a alphanumeric job id into the db it works. This is only happening when trying to update via the win form. Here is the code and thanks for your time...

    Code:
    //Build Commands ---------------------------------------------
    SqlCommand mySqlCommand = db.CreateCommand();
    int log_total = Convert.ToInt32( txt_total.Text) - Convert.ToInt32(starting_total) ;
    string date = String.Format("{0:yyyyMMdd}", DateTime.Now);
    
    
    // THIS ONE IS THE PROBLEM ------------------------------------
    string jobID = textBox1.Text;
    
    
    string update_log = jobID + "," + starting_total + "," + txt_total.Text + "," + log_total + "," + date; 
    
    mySqlCommand.CommandText =
    "INSERT INTO Log (Job, Start, Finish, Total, Date)" +  " VALUES (" + update_log + ")"; 
                                  
    
    
    // Open, Execute, Close ----------------------------------------
    
    db.Open();
    
    SqlDataReader mySqlDataReader = mySqlCommand.ExecuteReader();
    
    db.Close();
  • Paul73
    New Member
    • Sep 2007
    • 13

    #2
    Nevermind. I was missing a ' around the JobID field.

    Comment

    • Curtis Rutland
      Recognized Expert Specialist
      • Apr 2008
      • 3264

      #3
      I'd really suggest that you use String.Format or use parameters. I know it's just for you, but using either of those makes your code far more maintainable and readable, and it would be much easier to spot those errors. In fact, if you used parameters, that error would never have even come up.

      Comment

      • Paul73
        New Member
        • Sep 2007
        • 13

        #4
        Originally posted by insertAlias
        I'd really suggest that you use String.Format or use parameters. I know it's just for you, but using either of those makes your code far more maintainable and readable, and it would be much easier to spot those errors. In fact, if you used parameters, that error would never have even come up.
        Thanks, I'll take your advice. Have a great weekend!

        Comment

        Working...