0

I met a strange problem. I wanted to add string and string but it did not add together in actual.

Below is my code:

sql = "insert into Table (a,b,c,d) values ('" + a.value + "',b,'" + c.value + "',0)"

I use MessageBox to show this string and it just shows

insert into Table (a,b,c,d) values ('a

How can I modify it?

Ken White
  • 123,280
  • 14
  • 225
  • 444
CYB
  • 1,106
  • 15
  • 36
  • What is the value of `a.value`? – Yuriy Galanter Sep 14 '13 at 04:22
  • 2
    Please do a search on "VB string concatenation" for the basics of the language, and then do your yourself a **major** favor and research "parameterized queries" and "SQL injection" for the proper way to handle your SQL. – Ken White Sep 14 '13 at 04:24

2 Answers2

0

Always use an ampersand "&" when appending strings in VB.NET.

Change the code to

sql = "insert into Table (a,b,c,d) values ('" & a.value & "',b,'" & c.value & "',0)"
Farax
  • 1,447
  • 3
  • 20
  • 37
  • 3
    Or better yet, change to use a parameterized statement and eliminate the concatenation totally (and reduce the risk of SQL injection at the same time). – Ken White Sep 14 '13 at 04:22
  • Thanks for reply. However, if I use `&`, it still breaks at `a.value`. – CYB Sep 14 '13 at 05:45
  • @CYB what is `a`? and what is the value of `a.value`? – Damith Sep 14 '13 at 06:24
  • @Damith It's a GUID string and it will be like `a7sh1-aj2d9-sj1hs-dj2h`. – CYB Sep 14 '13 at 06:39
  • @Damith Yes, I've tried your answer, thank you, but it still did not work. – CYB Sep 14 '13 at 06:47
  • @CYB Debug and check at run time what you have for those values, add Quick watch to your statement and try to change it and test, play around debugging you can find answer your self. – Damith Sep 14 '13 at 06:52
  • just a hunch, but does it make a difference if you try stringbuilder instead of taking sql as a string? – Farax Sep 14 '13 at 10:42
0

you ca use + as below

sql = "insert into Table (a,b,c,d) values ('" + a.value.ToString() + "',b,'" + c.value.ToString() + "',0)"

you need to convert the values to string if they are already not strings

but here you specify ,b, without '', if it is string then you need to add that as below

sql = "insert into Table (a,b,c,d) values ('" + a.value.ToString() + "','b','" + c.value.ToString() + "',0)"

if you using & operator then you don't need to convert to strings. read more about this check this link.

all above for string Concatenation but regarding SQL statement I would recommend you to use parameterized SQL statement.

How do I create a parameterized SQL query? Why Should I?

Community
  • 1
  • 1
Damith
  • 62,401
  • 13
  • 102
  • 153