MySqlConversionException issue - mysql

i want to insert date now into mysql database
i need to convert the format but it didn't worked
this is my code
Dim now As Datetime = Datetime.Now.ToString("yyyy-MM-dd")
but it didn't worked either
as i google this i found out that the problem is because the parameter in my connection string AllowDateTimeZero=True
but when i tried to add it in my conn string, it stil didn't worked. could someone help me about this
i've spent 2 hours trying to fix this, but it's not worked..
thanks before

In VB, a DateTime data type holds the number if TICKs that have occured since 1/1/0001 12:00:00 AM. When you convert the DateTime.Now into a string, then put it into another DateTime, VB must convert the string "1985-12-31" into the number of ticks.
The code you posted...
Dim now As Datetime = Datetime.Now.ToString("yyyy-MM-dd")
...does nothing except introduce the possibility of issues due to culture difference in DateTime.
What you should have done is posted the code you use to insert the data into MySQL. If you are using a command and a non-parameterized INSERT:
INSERT INTO MyTable (MyDate) VALUES (" & Datetime.Now.ToString("yyyy-MM-dd") & ")
If it is parameterized, as it should be:
cmd.AddParameterWithValue("p1",Datetime.Now)
If you are using the EF or some type of DBML:
MyTable.MyDate = Datetime.Now

Related

Query of concatenation on Access [duplicate]

Any help that can be provided to a Access and VB noob would be greatly appreciated. What I'm trying to do is concatenate the values from one table and insert it as a comma delimited value into a field in another table. I'm trying to take all the server names that are say Linux boxes and concatenate them into a different field.
Table A looks like this
Machine Name | Zone | Operating System
----------------------------------------
Server01 Zone A Linux
Server02 Zone B Linux
Server03 Zone A Windows
Server04 Zone C Windows
Server05 Zone B Solaris
Table B has the field I want to insert into: Affected_Machine_Names.
Now, I've tried looking through the Concatenate/Coalesce posts, but the SQL view in Access doesn't like the Declare statements. My VB skills suck badly and I can't seem to get the code to work in VB for Applications. Unfortunately, I can't get this database converted into our SQL farm cause I don't have a server available at the moment to host it.
Can anyone point me in the right direction?
You can use Concatenate values from related records by Allen Browne for this. Copy the function code from that web page and paste it into a new standard module. Save the module and give the module a name different from the function name; modConcatRelated would work.
Then I think you should be able to use the function in a query even though you're not proficient with VBA.
First notice I changed the field names in TableA to replace spaces with underscores. With that change, this query ...
SELECT
sub.Operating_System,
ConcatRelated("Machine_Name", "TableA",
"Operating_System = '" & sub.Operating_System & "'") AS Machines
FROM [SELECT DISTINCT Operating_System FROM TableA]. AS sub;
... produces this result set:
Operating_System Machines
Linux Server01, Server02
Solaris Server05
Windows Server03, Server04
If you can't rename the fields as I did, use a separate query to select the distinct operating systems.
SELECT DISTINCT TableA.[Operating System]
FROM TableA;
Save that as qryDistinctOperatingSystems, then use it in this version of the main query:
SELECT
sub.[Operating System],
ConcatRelated("[Machine Name]", "TableA",
"[Operating System] = '" & sub.[Operating System] & "'") AS Machines
FROM qryDistinctOperatingSystems AS sub;
This is a fairly basic VBA function that will loop through every row in a column, and concatenate it to a comma-delimited result string. i.e., for your example, it will return "Server01, Server02, Server03, Server04, Server05". (Don't forget to replace the column and table names)
Function ConcatColumn(OS As String) As String
Dim rst As DAO.Recordset
Set rst = CurrentDb.OpenRecordset("Select * from TableA")
Dim result As String
'For every row after the first, add a comma and the field value:
While rst.EOF = False
If rst.Fields("Operating System") = OS Then _
result = result & ", " & rst.Fields("MyValue")
rst.MoveNext
Wend
'Clean it up a little and put out the result
If Left(result, 2) = ", " Then result = Right(result, Len(result) - 2)
Debug.Print result
ConcatColumn = result
End Function
To use this,
1. ConcatColumn("Windows") will return "Server04, Server03"
2. ConcatColumn("Linux") will return "Server01, Server02"
3. ConcatColumn("Solaris") will return "Server05"
4. ConcatColumn("") will return "".

How to save and retain Date milliseconds (MySQL)

I need to generate the current Date in vb.net that's have also the millisecond. Actually I use:
Date.Now
But this returns a simple date as 28/12/2015 16:53, I want also the millisecond something like:
28/12/2015 16:53:48640864
I tried with:
Public Shared Function MillisecondsDate()
Return Date.Now.ToString("HH:mm:ss.fffffff")
End Function
but this returns a bad result:
16:53:56.9884043
I need a format compatible with MySql for an accurate lastUpdated field. Any ideas?
From comments: my db field is a timestamp and I fix temp using a varchar instead a datetime or timestamp
A TimeStamp column isnt quite the same as a DateTime column. According to the Documentation:
MySQL converts TIMESTAMP values from the current time zone to UTC for storage, and back from UTC to the current time zone for retrieval. (This does not occur for other types such as DATETIME.)
It is something you may never see, even MySQL WorkBench UI converts it back.
Fractional Seconds
The issue of Fractional Seconds is something else. When defining a column as DateTime or TimeStamp, fractional seconds are dropped by default, for compatibility with older versions.
Rather than defining any sort of Date column as string/text/varchar - and of course having to parse it back - you can define either type to retain fractional seconds. In MySQL 5.6.4+, you can use: DATETIME(n) or TIMESTAMP(n) (yes, thats why the parens show in the UI dropdown list). Where n is the number of fractional digits to store (0-6). For .NET, 3 would equate to milliseconds. After that, the WorkBench UI shows the milliseconds as well:
StartDate is DateTime(0) (no fractionals)
LastUpdated is TimeStamp(3)
Foo is TimeStamp(6)
Trigger
A LastUpdated column would seem best managed by the database so you don't have to do so via code -- or forget to do so!. This is pretty simple using a default value and a Before_Update trigger:
Define the column as TIMESTAMP(3)
Specify CURRENT_TIMESTAMP(3) as the default value
ADD COLUMN LastUpdated TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3) COMMENT '';
This would automatically set the LastUpdated value on new items added to the current time (UTC etc) with milliseconds (TIMESTAMP(6) might be better, but the question only frets about ms). Be sure to specify the same number of digits in the default.
Then, rather than passing DateTime.Now manually (or converting to string) when updating each record, add a trigger to update the column for you. In MySql Workbench:
CREATE DEFINER=`root`#`localhost` TRIGGER `test`.`demo_BEFORE_INSERT` BEFORE INSERT ON `demo` FOR EACH ROW
BEGIN
SET new.LastUpdated := now(3);
END
Most of that is boilerplate that the UI Tool creates. You just need to type:
SET new.LastUpdated := now(3);
For this type of column, you'd can add the same thing on the BEFORE_INSERT trigger in place of a default value. In MySQL WorkBench, click the "Triggers" tab when viewing the table definitions - just add the SET statement.
Test Code
This shows the fractional milliseconds making the round trip from code to db and back, and shows that the trigger works (uses the table shown above):
Dim Usql = "UPDATE Demo SET Foo = #p1 WHERE Id=5"
Dim Ssql = "SELECT Name, StartDate, Foo, LastUpdated FROM Demo WHERE Id=5"
Dim dtVar As DateTime = DateTime.Now
Console.WriteLine("DT ms in code var: {0}", dtVar.Millisecond)
Using dbcon = GetMySQLConnection()
dbcon.Open()
Using cmd As New MySqlCommand(Usql, dbcon)
cmd.Parameters.AddWithValue("#p1", dtVar)
cmd.ExecuteNonQuery()
End Using
Using cmd As New MySqlCommand(Ssql, dbcon)
Using rdr As MySqlDataReader = cmd.ExecuteReader
If rdr.HasRows Then
rdr.Read()
Dim tempDT = rdr.GetMySqlDateTime(1) ' DateTime(0)
Console.WriteLine("DT.MS from DB {0}", tempDT.Millisecond)
Dim mydt = rdr.GetMySqlDateTime(2) ' TimeStamp(6)
Console.WriteLine("Micro from DB {0} ", mydt.Microsecond)
' either get method retains the ms TimeStamp(3)
Dim lstupD = Convert.ToDateTime(rdr("lastUpdated"))
Console.WriteLine("MS from trigger {0}", lstupD.Millisecond)
End If
End Using
End Using
End Using
Result:
DT ms in code var: 615
DT.MS from DB 0
Micro from DB 615413
MS from trigger 615
The columns defined to store fractional seconds do so down to microseconds (ticks). Note that the Update SQL doesn't reference the LastUpdated column, yet it is updated courtesy of the trigger. If you are step-debugging and using a variable as above the trigger time can vary from the others because time is passing as you step through.
Try this
Public Shared Function MillisecondsDate()
Return Date.Now.ToString("dd/MM/yyyy HH:mm:ss.fff")
End Function
Try this function:
Public Shared Function MillisecondsDate()
Return DateTime.UtcNow.ToString("dd/MM/yyyy HH:mm:ss.fff")
End Function

Comparing string with SmallDateTime used to work

I'm trying to debug an old VB6 program at my job. It's full of bugs and hardcoded stuff.
The program is connecting on a SQL Server 2005 database to read and write info using stored procedures.
Since the program is still being used while I'm working on it, I made a backup of the database to test some things and restored it in my version of SQL Server 2008. Everything was working fine.
When I came in the next morning, I got an error I didn't have the previous night even though the program wasn't used in the night.
The problem :
"exec dbo.sp_Get_Wait_Data '" & DateEx & "'"
DateEx is a string containing "2012/06/14"
The stored procedure :
[sp_Get_Wait_Data] #Datest as char(10)
AS
SELECT
(A lot of column names here)
FROM
Fiche
LEFT JOIN
voyage ON fcid = vofiche
LEFT JOIN
client on fcaccount = cusnov
WHERE
fcdate = #Datest
AND (void is null or (void > 0 and (void <> 999 and void <> 1000 and void <> 998)))
AND ((fcremarques NOT LIKE '%SYSANNULATION%' OR
fcremarques IS NULL)
AND fcrettime IS NOT NULL)
ORDER BY
FcTime, FcOrgSite, fcdessite
The error message :
The conversion of a varchar data type to a smalldatetime data type resulted in an out-of-range value
So the error is here fcdate=#Datest in the stored procedure. I tried adding this line in the stored procedure
SELECT convert(datetime, #Datest, 120)
which worked like a charm for the convertion within the query but caused a few hundred other errors within the program when other queries tried to access this variable so it is not an option.
Any idea why this query was working perfectly yesterday and now it's giving me this error? Thanks in advance.
You probably have set dateformat dmy when connecting to the copy of your database. The date format is set implicitly by the language used. set language.
You could change the format of the parameter to YYYYMMDD which will be safe regardless of set dateformat or even better, change your parameter to datetime.
If that is not an option you can rewrite your query using where fcdate=convert(datetime, #Datest, 111)

Concatenate fields from one column in one table into a single, comma delimited value in another table

Any help that can be provided to a Access and VB noob would be greatly appreciated. What I'm trying to do is concatenate the values from one table and insert it as a comma delimited value into a field in another table. I'm trying to take all the server names that are say Linux boxes and concatenate them into a different field.
Table A looks like this
Machine Name | Zone | Operating System
----------------------------------------
Server01 Zone A Linux
Server02 Zone B Linux
Server03 Zone A Windows
Server04 Zone C Windows
Server05 Zone B Solaris
Table B has the field I want to insert into: Affected_Machine_Names.
Now, I've tried looking through the Concatenate/Coalesce posts, but the SQL view in Access doesn't like the Declare statements. My VB skills suck badly and I can't seem to get the code to work in VB for Applications. Unfortunately, I can't get this database converted into our SQL farm cause I don't have a server available at the moment to host it.
Can anyone point me in the right direction?
You can use Concatenate values from related records by Allen Browne for this. Copy the function code from that web page and paste it into a new standard module. Save the module and give the module a name different from the function name; modConcatRelated would work.
Then I think you should be able to use the function in a query even though you're not proficient with VBA.
First notice I changed the field names in TableA to replace spaces with underscores. With that change, this query ...
SELECT
sub.Operating_System,
ConcatRelated("Machine_Name", "TableA",
"Operating_System = '" & sub.Operating_System & "'") AS Machines
FROM [SELECT DISTINCT Operating_System FROM TableA]. AS sub;
... produces this result set:
Operating_System Machines
Linux Server01, Server02
Solaris Server05
Windows Server03, Server04
If you can't rename the fields as I did, use a separate query to select the distinct operating systems.
SELECT DISTINCT TableA.[Operating System]
FROM TableA;
Save that as qryDistinctOperatingSystems, then use it in this version of the main query:
SELECT
sub.[Operating System],
ConcatRelated("[Machine Name]", "TableA",
"[Operating System] = '" & sub.[Operating System] & "'") AS Machines
FROM qryDistinctOperatingSystems AS sub;
This is a fairly basic VBA function that will loop through every row in a column, and concatenate it to a comma-delimited result string. i.e., for your example, it will return "Server01, Server02, Server03, Server04, Server05". (Don't forget to replace the column and table names)
Function ConcatColumn(OS As String) As String
Dim rst As DAO.Recordset
Set rst = CurrentDb.OpenRecordset("Select * from TableA")
Dim result As String
'For every row after the first, add a comma and the field value:
While rst.EOF = False
If rst.Fields("Operating System") = OS Then _
result = result & ", " & rst.Fields("MyValue")
rst.MoveNext
Wend
'Clean it up a little and put out the result
If Left(result, 2) = ", " Then result = Right(result, Len(result) - 2)
Debug.Print result
ConcatColumn = result
End Function
To use this,
1. ConcatColumn("Windows") will return "Server04, Server03"
2. ConcatColumn("Linux") will return "Server01, Server02"
3. ConcatColumn("Solaris") will return "Server05"
4. ConcatColumn("") will return "".

MySQL - Passing UTC timestamps to sprocs via JDBC

I have a MySQL Server set to UTC (##global.time_zone = '+00:00') and a table with a DATETIME column in which I store dates in UTC. I'm having problems getting UTC dates to come through when I call a stored procedure via JDBC. Example:
java.util.Date now = new java.util.Date();
sproc = conn.prepareCall("{call TzTestInsert(?)}");
sproc.setTimestamp(1, new java.sql.Timestamp(now.getTime()), Calendar.getInstance(TimeZone.getTimeZone("GMT+00:00")));
sproc.execute();
The TzTestInsert sproc simply takes a DATETIME and inserts it into the table.
I'd expect the database to now hold my current time in UTC, but in fact it holds the current time for my timezone.
If I change the sproc to take a string it works...
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
dateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
...
sproc.setString(1, dateFormat.format(now));
but I'd rather use the correct type in the sproc.
Also works if I bypass the sproc, but again not my preferred solution...
String sql = "INSERT INTO TzTest VALUES('" + dateFormat.format(now) + "') ;
With the original sproc I have the same issue if I use a TIMESTAMP datatype in the sproc and table, which isn't surprising with the server in UTC since any timezone conversions specific to MySQL TIMESTAMP should be noops.
Calling the sproc from a MySQL Workbench connection works fine, e.g.
CALL TzTestInsert(UTC_TIMESTAMP());
Seems like the problem is in JDBC. I've looked at the various timezone connection parameters and haven't found any that make a difference.
I must be missing something basic - lots of people do this, right?
Solution was to pass the JDBC driver "useLegacyDatetimeCode=false". See mysql bug http://bugs.mysql.com/bug.php?id=15604
Looks like they left the old code in the driver for backwards compatibility.