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
Related
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.
I'm a beginner. I created a database in vb.net and I need to build a query, in the SQL Statement - Table Adapter, which returns records even if parameters are NULL in one or more textbox. To be clear, I have several textboxes (related to fields) with which I can filter record results and I want to refine my research as much as I fill textboxes, reverse if I fill just one of them randomly.
Sorry if I confused you, but I guess you get it anyway.
In its simplest form (assuming SQL server param concepts)
-- Define your columns to pull back/display
select t1.column1, t1.column2, t1.column3...
-- Define the table, give it an alias if you're using more than one or it has a silly name
from thetable t1
-- Apply filters
where
-- For each textbox/column search combo, do this...
(column1 = #field1 or #field1 is null)
or -- If the filter is restrictive, use AND here
(column2 = #field2 or #field2 is null)
or -- If the filter is restrictive, use AND here
...
I would dump the table adapter for this requirement.
I am building the sql string using a StringBuilder. StringBuilder objects are mutable, String is not.
To run this Code
1. I assumed Sql Server. If this is not the case change all the data object (Connectio and Command) to the proper provider.
Add your connection string to the constructor of the connection.
Add your table name where it says "YourTable"
I just used TextBox1 etc. as control names. Use your actual control names
Replace Field1, Field2 etc. with your actual column names.
The parameter names (by convention, they start with #) can be anything you want as long as they match the name you add to the Parameters collection.
You will have to check your database for the actual datatypes of the fields. Be sure to convert the TextBox values to the compatible type. TextBox.Text is a string so it will be compatible to .VarChar but note number types or dates.
I added a Debug.Print to check what the Sql string looks like. Be cautious about where I have spaces when building the string. You can see the result in the immediate window (available from Debug menu).
If you don't already have a DataGridView on your form, add one so you can see the reults of your query.
Finally, always use parameters, use Using...End Using blocks, and open your connection at the last minute.
Private Sub RunDynamicQuery()
Dim sb As New StringBuilder
Dim AndNeeded As Boolean
Dim dt As New DataTable
Using cn As New SqlConnection("Your connection string")
Using cmd As New SqlCommand
sb.Append("Select * From YourTable Where ")
If Not String.IsNullOrEmpty(TextBox1.Text) OrElse Not String.IsNullOrWhiteSpace(TextBox1.Text) Then
sb.Append("Field1 = #Field1")
cmd.Parameters.Add("#Field1", SqlDbType.Int).Value = CInt(TextBox1.Text)
AndNeeded = True
End If
If Not String.IsNullOrEmpty(TextBox2.Text) OrElse Not String.IsNullOrWhiteSpace(TextBox2.Text) Then
If AndNeeded Then
sb.Append(" And")
End If
sb.Append(" Field2 = #Field2")
cmd.Parameters.Add("#Field2", SqlDbType.VarChar).Value = TextBox2.Text
AndNeeded = True
End If
If Not String.IsNullOrEmpty(TextBox3.Text) OrElse Not String.IsNullOrWhiteSpace(TextBox3.Text) Then
If AndNeeded Then
sb.Append(" And")
End If
sb.Append(" Field3 = #Field3")
cmd.Parameters.Add("#Field3", SqlDbType.VarChar).Value = TextBox3.Text
AndNeeded = True
End If
sb.Append(";")
cmd.Connection = cn
Debug.Print(sb.ToString)
cmd.CommandText = sb.ToString
cn.Open()
dt.Load(cmd.ExecuteReader)
End Using
End Using
DataGridView1.DataSource = dt
End Sub
there's anyone can help me with my vb.codes? i'm new in vb.net and i want to know how to add data in mysql database using n-tier in vb.net. this is may current code in adding data:
Data Layer:
Public Function addData() As DataTable
Dim myCommand As String = "Insert Into tblItems VALUES (#Itemcode, #Itemname, #Itemdescription, #Itemtype, #Itempricing, #Itemonstock, #Itemprice, #Datemod)"
con.Open()
Dim sda As New MySqlDataAdapter(myCommand, con)
Dim dt As DataTable = New DataTable
sda.Fill(dt)
Return dt
End Function
sorry for my code. i really don't know how can i use that in BLL and PL. please help me. i really want to learn from all of you guys..
PS: sorry for my english i'm a 14 yr old and i want to learn programming. i did a research but i can't find what i'm really looking for. thanks in advance.
To insert a new record in a datatable you need to execute a command and provide the values to be sent to the database table.
You need something like this.
Public Function addData(itmCode as String, itmName as String.... omitted the other values) As Integer
Dim myCommand As String = "Insert Into tblItems VALUES " & _
"(#Itemcode, #Itemname, #Itemdescription, " & _
"#Itemtype, #Itempricing, #Itemonstock, #Itemprice, #Datemod)"
con.Open()
Dim cmd As New MySqlCommand(myCommand, con)
cmd.Parameters.AddWithValue("#ItemCode", itmCode)
cmd.Parameters.AddWithValue("#ItemName", itmName)
.... other parameters for the other values to insert will follow....
Dim rowInserted = cmd.ExecuteNonQuery()
return rowInserted
End Function
This requires that you pass to the function the values through a set of variables which values are added to the parameter collection of the command and finally execute the command.
The execution returns the number of records inserted/changed/deleted.
Notice also that your query doesn't specify a field list, so you need to pass the values to update every single field in the underlying datatable with the exact order.
I am using a WPF application to insert a student into my MS Access database.
I wanted to use a parameter with this code:
Dim sql As String = _
"INSERT INTO exams " & _
"VALUES (#student)"
Dim opdracht As OleDbCommand = New OleDbCommand(sql, connectie)
opdracht.Parameters.Add(New OleDbParameter("#student", 5))
but this doesn't work.
The only way i get it to work is this one:
Dim sql As String = _
"INSERT INTO exams " & _
"VALUES (" & student & ")"
' opdracht initialiseren
Dim opdracht As OleDbCommand = New OleDbCommand(sql, connectie)
To use this query I use the command, this is the point where I get my error.
opdracht.executeNonQuerry()
The table layout in MS Access looks like this:
And my application inserts the other values corectly but i left them out to keep a minimal example.
If you have a variable named student and you want to use its value for the parameter then you need to assign that variable as parameter's value
Dim sql As String = "INSERT INTO exams VALUES (#student)"
Dim opdracht As OleDbCommand = New OleDbCommand(sql, connectie)
opdracht.Parameters.AddWithValue("#student", student)
opdracht.ExecuteNonQuery()
Of course, I am assuming this because you say that the string concatenation version is working, and in that example you concatenate the value of a variable named student in your command text
Remember that with OleDb the name of your parameters is meaningless because OleDb use the position of the placeholder to pass the parameters' values, not the parameter name
EDIT Using INSERT INTO without specifying the column names works only if you add the parameters for all fields. Your database table contains other fields so you need to specify them or use a different syntax for the INSERT INTO
Dim sql As String = "INSERT INTO exams (Student) VALUES (#student)"
But this will fail also because you have the Student field part of your primary key. The fields that belong to a Primary Key cannot be null so you have no choice but add all the values required by the primary key
Dim sql As String = "INSERT INTO exams (Student, locaal, opleidingsOnderdeel) " & _
"VALUES (#student, #local, #oplei)"
.. add the parameter's value for student, local and oplei
However, I am a bit perplexed that the string concatenation works. What is the value of the variable student? You should get the same error as using the parameterized query with only one parameter.
I have an Access table which has a Number field and a Text field.
I can run a query like this:
SELECT * FROM Table ORDER BY intID ASC
//outputs 1,2,3,10
But when I try to run the same query through the .NET OleDB client, like this:
Private Sub GetData()
Using cnDB As New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & Path)
cnDB.Open()
Dim SQL As String = "SELECT * FROM Table ORDER BY intID ASC"
Dim cmd As New OleDbCommand(SQL, cnDB)
Dim dr As OleDbDataReader = cmd.ExecuteReader()
While dr.Read()
lst.Items.Add(dr.Item("intID") & " - " & dr.Item("strName"))
End While
cnDB.Close()
End Using
End Sub
I get items in the order 1,10,2,3.
What's going on here, and how can I have the data sort "naturally" (1,2,3,10) in both places?
try
SELECT * FROM Table ORDER BY CInt(intID) ASC
to explicitly tell Access to treat this as an integer and not a string. Obviously, something in the OleDbClient is seeing this field as a string (text field) and sorting accordingly.
I suspect the problem is your connection string. If you're connecting to an Access database and include IMEX=1 in your connection string, the provider will treat all data as string. As such, the ordering will order by the string value, giving you 1, 10, 2, 3, as opposed to leaving the intID as an integer, and ordering it in numerical order.
It looks like you're getting a lexical (alphabetic) order. This will be correct if something in your database or query thinks that is a varchar/text column type instead of a numeric type.