-2

I have verbatim string that have some variables contacanete with, my problem I always get this error from the compiler:

; expected

So how I can escape it properly?

int teacherId = sqlStatus = (int)sqlCmd.LastInsertedId;
sqlCmd.CommandText = @"INSERT INTO report (report_type, report_date, semester, report_details, teacher_id) 
                            VALUES (0, ""2018-01-01"", 1, '{
                              ""teacherId"": "" " + teacherId.ToString() + " "",   <=== error here (; expected)
                              ""mahderDate"": """",
                              ""teacherShool"": """",
                              ""baladia"": """",
                              ""wilaya"": """",
                              ""moufatecheReport"": """"
                            }'," + teacherId + ");";
H Aßdøµ
  • 2,925
  • 4
  • 26
  • 37
  • Thought of using string.Format? Or interpolated strings? Anyway in short you can escape characters using '\' – Dave Jan 01 '18 at 17:35
  • The proper way would be to use parameterized queries to avoid the possibility of SQL injections. – poke Jan 01 '18 at 17:36
  • 1
    Anyway, the problem here is that you are starting a new string after the `teacherId.ToString()`. But that string is not a multiline string: You need to place the `@` in front of the opening quote again. – poke Jan 01 '18 at 17:36
  • @Dave I tried '\' but still have same error. – H Aßdøµ Jan 01 '18 at 17:37
  • @poke I didn't use parameterized queries because I have a guarantee of what will be inserted to the database. – H Aßdøµ Jan 01 '18 at 17:38
  • 4
    Parametrized queries are better not only because they protect from sql injection, so I'd still use them here. – Evk Jan 01 '18 at 17:50

1 Answers1

0

Using @poke suggestion I managed to get it work with placing a double quote and @ in the line:

    int teacherId = sqlStatus = (int)sqlCmd.LastInsertedId;
    sqlCmd.CommandText = @"INSERT INTO report (report_type, report_date, semester, report_details, teacher_id) 
                                VALUES (0, ""2018-01-01"", 1, '{
                                  ""teacherId"": "" " + teacherId.ToString()  + "," + 
                               @" ""mahderDate"": """",
                                  ""teacherShool"": """",
                                  ""baladia"": """",
                                  ""wilaya"": """",
                                  ""moufatecheReport"": """"
                                }'," + teacherId + ");";
H Aßdøµ
  • 2,925
  • 4
  • 26
  • 37