How to insert single quote and comma in one column - vb.net

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

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.

Retrieving "Number" From Sql VB.NET System.Data.OleDb.OleDbException: 'Data type mismatch in criteria expression.'

If I want to retrieve a value that is saved as a number in an access database.
Im using the following:
Dim sql As String = "SELECT ArithmeticScore FROM " & tablename & " WHERE DateAscending = '" & todaysdate & "'"
Using connection As New OleDbConnection(getconn)
Using command As New OleDbCommand(sql, connection)
connection.Open()
scorevalue = CDec(command.ExecuteScalar()) 'Data type mismatch in criteria expression.
connection.Close()
End Using
End Using
MsgBox(scorevalue)
getconn = connection string as a string
scorevalue = Nothing as decimal
The field ArithmeticScore is set to Number in the table.
The exact value in the cell right now is 50, but the program should allow for any decimal value.
The error im getting is "Data type mismatch in criteria expression".
The criteria expression mentioned in the error message does not refer to the ArithmeticScore output. It's talking about the WHERE clause. Whatever you have for todaysdate does not match what the database is expecting for the DateAscending column.
Since OleDb is a generic provider, we don't know exactly what kind of database you're talking to, but most databases have a way to get the current date value in SQL: getdate(), current_timestamp, etc. Using that mechanism will likely solve the conflict, and there's no need to use string concatenation for this in the first place.
Dim sql As String = "SELECT ArithmeticScore FROM " & tablename & " WHERE DateAscending = Date()"
The other way you can fix this is with proper parameterized queries, which you should doing anyway. It's NEVER okay to use string concatenation to substitute data into an SQL query, and if you find yourself needing to think about how to format a date or number string for use in an SQL command, you're almost always doing something very wrong.

Inserting empty values as string to sql table

I have a project which has a Class which has some members as string which equal "". My teacher had shown examples with Class members declared as String = "NULL". I try to insert to SQL and I get this message:
Error insertion... Error converting data type varchar to numeric.
I know many will suggest to use parameterized values for inserting but I like to finish the way I started this.
I have tried to cast query string Object values with CDec, CInt, Cbit and still no clue how to do it right because I got Exceptions for trying to cast an "".
Also, I have changed to default values of members like this;
Dim NumberOfPackage As String = ""
instead of;
Dim NumberOfPackage As String = "NULL"
Some Columns in SQL table had ALLOW NULL checkBox set to NOT allowed, I changed the design of the Table to make it easier for insertion.
The field in database have been set to not null? I think that dbnull.value do what you want
I think I understand what is happening. Your variable NumberOfPackage contains numbers but since you want to insert NULL sometime, you made it a string.
NumberOfPackage = "23"
NumberOfPackage = "NULL"
"INSERT INTO table (column) VALUES (" & NumberOfPackage & ");"
But since you use a string, you might be trying to do
"INSERT INTO table (column) VALUES ('" & NumberOfPackage & "');"
Which would cause the error on NULL since your column is a number and it is trying to do
"INSERT INTO table (column) VALUES ('NULL');"
Stick with my first example (without the ') if you really want to concatenate strings but everything would be much easier if you used parameters. By using parameters, it would be easier to keep NumberOfPackage as a decimal or a decimal? and do proper math with it.
To insert a NULL value, it must be without the apostrophes like #RichBenner and #the_lotus state:
Dim myCommand As String
myCommand = "INSERT INTO dbo.Foo (Foo_Text) VALUES (NULL);"
'The query for an empty string would look like this
myCommand = "INSERT INTO dbo.Foo (Foo_Text) VALUES ('');"
col1 in my Builder database is datatype int and nulls are allowed. This is how it is done with Parameters. TextBox1 will hold the number of packages and TextBox2 the name. I used the object datatype so it could hold either DBNull.Value or an Integer.
Private Sub InsertRecord()
Dim myValue As Object
Dim myInt As Integer
If Integer.TryParse(TextBox1.Text, myInt) Then
myValue = myInt
Else
myValue = DBNull.Value
End If
Using cn As New SqlConnection(My.Settings.BuildersConnectio)
Using cmd As New SqlCommand("Insert Into Builders (BuilderName, col1) VALUES (#Name, #NoOfPackages);", cn)
cmd.Parameters.Add("#Name", SqlDbType.VarChar, 100).Value = TextBox2.Text
cmd.Parameters.Add("NoOfPackages", SqlDbType.Int).Value = myValue
cn.Open()
cmd.ExecuteNonQuery()
End Using
End Using
End Sub

VB String Concatenation Incomplete

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?

Data type to be used to store 10 digit mobile number?

In my current vb.net (visual studio 2010) project I am dealing with SQL Server CE data base.
For storing mobile numbers, I am using nvarchar data type for Mobile_no field.
while testing i have entered 1234567890 in field Mobile_no successfully..
But at the time of retrieval i am getting this error :
Expression evaluation caused an overflow. [Name of function (if known)=]
So what should i do to store mobile numbers in sql ce data base ?
EDIT :
Code for Insert :
Dim SQLquery As String
Dim enumber As String
enumber = 1234567890
insqertSql = "INSERT INTO tbl_cust(c_id,Mobile_no) VALUES(#CId, #Phno)"
Dim cmd As New SqlCeCommand(insqertSql, con)
cmd.Parameters.Add("#CId", c_id)
cmd.Parameters.Add("#Phno", enumber)
cmd.ExecuteNonQuery()
Query for retrieval :
SQLquery = "SELECT * FROM tbl_cust WHERE ePhone =" & txt_number.text
The problem is in the string concatenation in the retrieve query.
SQLquery = "SELECT * FROM tbl_cust WHERE ePhone =" & txt_number.text
Here, you miss the single quotes that should enclose a string value when used as a WHERE condition.
However, in your INSERT query you use a parameterized approach, why you don't use the same approach for the select?
SQLquery = "SELECT * FROM tbl_cust WHERE ePhone = #number"
Dim cmd As New SqlCeCommand(SQLquery, con)
cmd.Parameters.Add("#number", txt_Number.Text)
SqlCeDataReader reader = cmd.ExecuteReader()
........
If you use a parameterized query, the proper handling of string quotes, decimal numbers and date formatting is passed to the underlying framework code that knows better than you and me how to pass these values to the database engine. Also, the parameterized query remove any possibilities of Sql Injection.