VB String Concatenation Incomplete - vb.net

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?

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)"

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?

Related

How do I use a comma delimited string as query criteria on a numeric field

I've built a function that creates a comma delimited string from multiple selections in my list box. When I try to use this as the Where clause in my sql (in VBA) I get a 'type mismatch' error - because the field I'm using with the criteria is numeric. How do I resolve this?
example:
sql = "INSERT INTO tblItemsLibrary ( Constr, Description) ...
"WHERE (((tblItemsLibrary1.ItemsLibID) In (" & strSelectedRecords & ")));"
In the above example strSelectedRecords is coming in as "17,11,28" where the field is a long.
You can use LIKE:
INSERT INTO tblItemsLibrary ( Constr, Description)
...
WHERE "," & tblItemsLibrary1.ItemsLibID) & "," LIKE "*," & strSelectedRecords & ",*"
Actually you might want to adjust strSelectedRecords to start and end with *, and ,*.
If you are using SQL Server 2016 or above, the function string_split can be used:
SELECT *
FROM tblItemsLibrary
WHERE tblItemsLibrary1.ItemsLibID IN (select * from STRING_SPLIT(#numlist, ','))
Replace #numlist with your string 17,11,28
Another method is to construct dynamic sql and pass that on top of base sql statement:
EXECUTE('SELECT * FROM tblItemsLibrary1 WHERE ItemsLibID IN
('+#numlist+')')
Your SQL expression will result in:
INSERT INTO tblItemsLibrary ( Constr, Description)
...
WHERE (((tblItemsLibrary1.ItemsLibID) In (17,11,28)));
which is correct if ItemsLibID is numeric.
Thus, your error is probably caused by the values you try to insert.

MS Access / SQL : error in insert query statement

I am using MS Access 1997 version (.mdb file). On a daily basis, I need to insert values manually. In that file, there's a column Logical (Boolean data type). I am automate this template using SQL query instead of direct entry.
Below is my insert query:
Insert Into Data_CustomerTransmit_Tbl (Logical)
Values (" & Logicalnme & ")
Values:
Logicalnme - True
When I run this query in VBA in Excel, I get this error message
Syntax Error in Insert into Statement
Kindly confirm shall I use "Logical" as column name or this is the reserved keyword?
Thanks in advance.
There isn't a problem with your field name, you just need to enclose your INSERT column name in square brackets. You also need to choose a valid value in the VALUES clause:
INSERT INTO Data_CustomerTransmit_Tbl ( [Logical] )
VALUES (TRUE);
If you want to be prompted for the value to insert, you can use a parameter:
PARAMETERS [Please enter a Boolean value] YesNo;
INSERT INTO Data_CustomerTransmit_Tbl ( [Logical] )
VALUES ([Please enter a Boolean value]);
I presume you are trying to do this insert using VBA? If so, your syntax in building the SQL statement is correct, except you have some punctuation missing: double-quotes on each end.
"INSERT INTO Data_CustomerTransmit_Tbl (Logical) VALUES (" & Logicalnme & ")"
Further, as you have split the string over two lines (breaking before VALUES), you must also terminate the first line of the string with: ' " & _' (space,double-quote,space, ampersand, space, underscore) in order to indicate that the string continues to the next line. Then you begin the next line with double-quotes:
"INSERT INTO Data_CustomerTransmit_Tbl (Logical) " & _
"VALUES (" & Logicalnme & ")"
In VBA the code should look like this:
Docmd.RunSQL("INSERT INTO Data_CustomerTransmit_Tbl (Logical) VALUES (" & Logicalnme & ");"
The SQL query you alluded to - have you tried to execute it manually in the query editor using the same value(s) you are trying to pass from Excel? That would immediately provide more verbose feedback if there is an issue with the query or the data.
Regarding the Boolean field, make sure you are receiving a True/False that you are expecting, not a bit field, 0 and 1. I like to make quick log entries in a table or a file when troubleshooting to see the raw data.
Use Cbool function:
Insert Into Data_CustomerTransmit_Tbl (Logical)
Values (" & Cbool(Logicalnme) & ")
Add single quotes around values?
sql = "INSERT INTO Data_CustomerTransmit_Tbl (Logical) " & _
"VALUES ('" & Logicalnme & "')"
docmd.runsql sql

Insert Into Select SQL Server

I am trying to do a kind of insert into select statement. I want to insert one column as standard and the second through a select. However this is not working:
queryString = "INSERT INTO Words (Word, SortedId) VALUES ('" + words[i] + "', (SELECT TOP 1 SortedId FROM SortedWords WHERE SortedWord = '" + sortWord(words[i]) + "'))";
SortedWords is already filled with data. But at the moment i get this error
{"There was an error parsing the query. [ Token line number = 1,Token line offset = 50,Token in error = SELECT ]"}
Note:
not sure if i need the TOP 1 bit or not, get error either way. But I obvs only want to insert one row.
Change your query to
queryString = "INSERT INTO Words (Word, SortedId) SELECT '" + words[i] + "', (SELECT TOP 1 SortedId FROM SortedWords WHERE SortedWord = '" + sortWord(words[i]) + "')";
Also, instead of concatenating strings to get your query, use parameters to avoid SQL injection.
Try next and better practice to use a SqlParameters:
INSERT INTO words
(word,
sortedid)
(SELECT TOP 1 #Word,
sortedid
FROM sortedwords
WHERE sortedword = #SortedWord)
And before execiting query create a parameters(C#)
//Assume you have a SqlCommand object(lets name it command)
command.Parameters.AddWithValue("#Word", words[i]);
command.Parameters.AddWithValue("#SortedWord", sortWord(words[i]));

How to insert single quote and comma in one column

My code is as below '''a','b','c'''.
Dim abc As String = "''a','b','c''"
sqlselect.Connection = con
sqlselect.CommandText = "insert into table1(Name1) values ('" & abc & "')"
It gives the error:
Syntax error (missing operator)
in the query expression
You use parametrized query not string concatenation
Dim a As String = "'a', 'b', 'c'"
sqlselect.Connection = con
sqlselect.CommandText = "insert into table1(Name1) values (#a)"
sqlselect.Parameters.AddWithValue("#a", a)
sqlselect.ExecuteNonQuery()
This assuming you have only one column named Name1.
The parametrized queries are the only way to go because they offer protection against SQL Injections and help you treating the parsing of strings, dates, decimal numbers

trying to insert values into table

I am trying to inserting value enter in textbox into table like this
"INSERT INTO guestpasstypes(guestPassType_Name) VALUES('"+tbPassType.Text"'");
it was giving error like ";" missed
"Insert into guestpasstypes (guestPassType_Name) values ('" + tbPassType.Text + "')"
You are missing a concatenation operator:
"Insert INTO guestpasstypes(guestPassType_Name)values('" + tbPassType.Text + "');";
INSERT INTO guestpasstypes(guestPassType_Name) VALUES ('"+tbPassType.Text+"')"
The second quote should be outside the parantheses
If your going to carry on with this type of programming use
"Insert INTO guestpasstypes(guestPassType_Name)values('"+tbPassType.Text"')";
Otherwise, you should definitely look into sanitizing your sql.