How to cast DB2 Timestamp to vb.net date? - vb.net

When I populate my vb.net gridview using DB2 SQL, it displays DB2 Timestamp as:
2020-08-25-14.59.11.000000
^ What's the cleanest way to cast that as a vb.net Date? FWIW, this works:
Dim mydate As Date = CDate("2020-08-25 14:59:11.000000")
But, the colons in 14:59:11 do not exist, the string I'm working with has 14.59.11
Any help greatly appreciated.
Edit:
As requested,
screenshot of what data looks like when queried in AS400
Edit2:
Dim strSelect As String = "" &
"SELECT SUBMITTIME " &
"FROM MYTABLE " &
"WHERE EFYEAR=" & Now.Year & " AND EFMONTH=" & Now.Month
Dim dt As DataTable = SQL.Get_DataTable(strSelect)
grv.DataSource = dt
grv.DataBind()
Get_DataTable is just using OleDbConnection, OleDbCommand, OleDbDataAdapter, etc to fill a DataTable.

You can't cast something as a type that it isn't. The whole point of casting is that you don't change the object but rather the way you access the object. If you're changing the object then it is a conversion, not a cast.
If you want to convert something then the first step is to know what you're converting from. If you are converting from a String of a known format to a DateTime then you would use Date.ParseExact.
If the data is in a DataTable, add a new column with the appropriate data type, do the conversion in a loop and then, if appropriate, remove the original column.
myDataTable.Columns.Add("DataColumn", GetType(Date))
For Each row As DataRow In myDataTable.Rows
row("DateColumn") = Date.ParseExact(CStr(row("TextColumn")), "yyyy-MM-dd-HH.mm.ss.ffffff", Nothing)
Next
myDataTable.Columns.Remove(myDataTable.Columns("TextColumn"))

Related

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.

Excel to VB: Can't read the zero behind

I'm doing a connection with excel and I have a problem when I try to use an ID that have 0 behind...
I'm using a ListBox and add the IDs from the excel's worksheet as items. IDs have 9 numbers, like "123456789" or "098765430". So that I remove the last 4 characters to search the IDs with the same 5 numbers and add in another ListBox. It works fine, except with the codes with 0 (zero) behind.
Dim ConnectionString As New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0; Data Source=" & Application.StartupPath & "\Tabela_Precos.xlsx; Extended Properties=Excel 12.0;")
ConnectionString.Open()
Dim ds As New DataSet
Dim dt As New DataTable
ds.Tables.Add(dt)
Dim da
For i = 0 To Form1.ListBox1.Items.Count - 1
Dim str As String = Compras.ListBox1.Items(i).ToString
Dim prod As String = str.Remove(str.Length - 4)
da = New OleDbDataAdapter("SELECT * FROM [Sheet1$] WHERE ID like '%" & prod & "%'", ConnectionString)
ListBox1.Items.Add(dt.Rows(i).Item(0))
Next
Your Excel file has the ID column entered as integer values, but is formatted for left-zero padding to present as a nine character field. Your Excel db connection is reading the values as numbers (type Double, even-though they are integers). Your original select statement is implicitly convert ID to a string for the Like comparison; however, this conversion does not now you want left-zero padding. To use this type of comparison, you need to format ID yourself.
Select * From [sheet1$] Where (Format([ID], ""000000000"") Like '" & prod & "%')"
As you have indicated in the comments above, this works. However, it is not the most efficient in terms of speed. Since ID is numeric, it should be faster to do a numeric comparison. You have already defined a String variable named prod and the following solution uses that variable to prepare a numeric value for use in constructing an alternate select based on your criteria.
Dim prodNum As Int32 = Int32.Parse(prod) * 10000I
Then the Select statement would become:
"Select * From [sheet1$] Where ((([ID]\10000) * 10000)=" & prodNum.ToString & ")"
These examples use a concatenated select statement, and ideally you would not do it this way, but rather use a parameterized statement with replacement values. I'll leave that exercise up to you to perform.

sql from vb cannot convert to date

Hi i'm trying to convert this line to get list of people active over todays date but cannot get it to work
adapter.SelectCommand = New SqlCommand( _
"select * from klijent where convert(varchar,convert(datetime,replace('" & DateTimeUgovora.Value.ToString & "','#','')),111) >= convert(varchar,getdate(),111)", myConn)
error is conversion of varchar data type to a datetime data type resulted in an out-of-range value.
my string that I get from front is
"29.11.2013. 19:41:08"
I searched everywhere and cannot find the answer please help
You should not need to convert the datetime value to a string, because in SQL you can compare datetime values directly. This is much more stable as it doesn't depend on locale settings. I don't fully understand your SELECT clause as even if the comparison works, it will return either all the rows in the table or none.
However, if you want to use the table column Kli_Ugovor_do in your comparison, you can change your statement to this:
adapter.SelectCommand = New SqlCommand( _
"select * from klijent where Kli_Ugovor_do >= getdate()", myConn)
Btw: in your statement you included the value of the combobox by string concatenation. You should get used to including parameters in your statements in order to avoid SQL injection attacks.
So if you want to use the value of the DateTimePicker, your code should look similar to this:
adapter.SelectCommand = New SqlCommand( _
"select * from klijent where Kli_Ugovor_do >= #dt", myConn)
adapter.SelectCommand.Parameters.AddWithValue("#dt", dateTimeUgovora.Value)
I just created a quick console application with the string mention by you. This may be helpful.
Imports System.Globalization
Module Module1
Sub Main()
Dim myDateString As String = "29.11.2013. 19:41:08"
myDateString = myDateString.Replace(".", "")
Dim myDate As DateTime = DateTime.ParseExact(myDateString, "ddMMyyyy HH:mm:ss", CultureInfo.InvariantCulture)
Console.WriteLine(myDate.ToString())
Console.ReadLine()
End Sub
End Module
I created a quick module for tsql as well, maybe it will help:
Declare #dt varchar(20)
set #dt = '29.11.2013. 19:41:08'
select convert(datetime, Replace(#dt, '. ', ' '), 103)

where clause in select statement - datetime issues

I want to put a where clause in my select statement based on the year and month of a timestamp field in my db
I have a month and a year dropdownlist which give me the following string 01/2012
The date format in my db is "2012-01-01 00:00:00" but when I select an individual date and put it in a message box it converts to "01/01/2012"
I've altered my select statement below to reflect the converted date. However Im still not given the correct details. Any ideas? Is there a particular format that I need to use when dealing with a timestamp field? Can I even use the "Right" function in a select statement?
Dim newRecordDate As String = val1 & "/" & ComboBox2.SelectedValue
Dim sql2 As String = "Select CatA, CatB, CatC, Cost, Currency, MarketingCode, Comment, RecordDate from vw_tblP_Usage_Details where puid = '" & puid & "' right(RecordDate, 7) = '" & newRecordDate & "'"
I say use parameters and the SqlParameter class to pass parameter values to sql server from .NET client instead of using concatenation and string formatting. It makes life easier.
Something Like This:
Dim myDate As Date = DateTime.Now
Dim sql As String = "Select * from SomeTable where MyDate = #some_param"
Using Command As New SqlClient.SqlCommand(sql)
Command.Parameters.AddWithValue("#some_param", myDate)
Using reader As SqlClient.SqlDataReader = Command.ExecuteReader()
'other code here
End Using
End Using

Sorting numbers in Access and .NET

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.