i want to insert a string as date format in mysql table using vb.net.my code is given below.but i always get an error .the string is stored in an array.
mycode
------
Dim sdfsa As String = Convert.ToDateTime(newarray(i + 17)).ToShortDateString().ToString("yyyy-MM-dd")
Dim newdate As Date = DateTime.ParseExact(sdfsa, "yyyy-MM-dd", System.Globalization.CultureInfo.InvariantCulture)
datarw("date_of_birth") = newdate
Are the Users inputting this information directly?
if they are why don't you input have them input the value in a masked text box?
This Link Could Help
Try this:
my_date =Format(Now,"yyyy-MM-dd")
Example
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim year, month, day As Integer
Dim date_value As Date
Dim date_final_to_mySQL As String
date_value = DateTimePicker1.Value
year = date_value.Year
month = date_value.Month
day = date_value.Day
date_final_to_mySQL = year & "-" & month & "-" & day
MessageBox.Show(date_final_to_mySQL)
End Sub
Only need create a button1 and datetimepicker1
Final Result
Related
I have the following code and have been asked to remove the user input box and automate pulling in files. One issue is if the current day is Monday, we would need Friday's date pulled in (not yesterday). I am sorry for being extremely basic, but I believe I would need to replace InputBox("Input Date") with something like DateAdd(Day, DateDiff(Day, 1, GETDATE()), 0) - but it does not like Day or DD.
Any ideas? (and thank you for being patient with me in advance)
DoCmd.SetWarnings False
Dim InvDateStr As String
Dim InvDate As Date
Dim Directory_Sheets As String
Dim filename_sheets As String
Dim db As Database
Dim rst As DAO.Recordset
Dim startdate As Date
Dim EndDate As Date
'startdate = #9/23/2010#
'enddate = #1/12/2011#
'InvDate = startdate
'Do Until InvDate = enddate
InvDateStr = InputBox("Input Date")
If InvDateStr = "" Then
Exit Sub
End If
InvDate = CDate(InvDateStr)
Directory_Sheets = FilePath & "Inventory_Surveys\"
On Error Resume Next
' Pull Stores with Inventory
I'm only going to do the date part, you can implement it:
InvDate = Date - 1 'Yesterday
Do While Weekday(InvDate, vbMonday) > 5 'Saturday or Sunday
InvDate = InvDate - 1
Loop
I want to run a for-loop from sometime to some specific time. Let's say from the first day of the year to the last day:
I am given the year and I need to add the month and the day to it:
I am trying to concatenate into a full date string and the compiler keeps throwing errors:
dim dt as Date
dim rs as recordset
set rs = currentdb.openRecordset("select max(date) as dan from Atbl")
for dt = #1/1/year(now)# to #2/2/Year(rs!dan)#
msgbox dt
Next
any help is appreciated. or any hint is welcome
DateSerial should make this easier.
Give it values for year, month, and day in that order, and it will give you back the corresponding date as a Date/Time value.
for dt = DateSerial(Year(Date), 1, 1) to DateSerial(rs!dan, 2, 2)
msgbox dt
Next
Nevermind, I found a solution quite fast: This works fine
dim dt as Date
dim rs as recordset
set rs = currentdb.openRecordset("select max(date) as dan from Atbl")
'save the first day as string first
Dim firstDay As String
firstDay = "1/1/" & Year(Now)
'convert to date
Dim firstDate As Date
firstDate = CDate(firstDay)
'save as string
Dim lastDay as string
lastDay = "2/2/" & Year(rs!dan)
'convert to date
Dim lastDate As Date
lastDate = CDate(lastDay)
'works fine in here
for dt = firstDate to lastDate
msgbox dt
next
How to get the number of the week in datetimepicker just like in Mysql just use the function WEEK()
and it will return the week number, simple as that.
example.
datetimepicker1.text = "9/9/2014"
'returns 36
just like in mysql. example.
WEEK(9/9/2014)
`returns 36
You can use Calendar.GetWeekOfYear
Dim dt = datetimepicker1.Value
Dim dateInfo = Globalization.DateTimeFormatInfo.CurrentInfo
Dim c = dateInfo.Calendar
Dim week = c.GetWeekOfYear(dt, dateInfo.CalendarWeekRule, dateInfo.FirstDayOfWeek)
Good day everyone.
This is another problem of mine. Since the first problem has been solved by the kind Sir Tim Schmelter. I would ask another set of questions. Thank you to those who will help
I have two problems:
My first problem now is with regards to the date. How do I convert the date from the text file so it would be inserted in the MySQL database? Its original form in the text file is ( 0246,04/16/2013,01:00,O ) and I don't know how to convert it
My second problem is I did change the values of the columns in the database to its rightful form (date to date, id to int) but whenever I try to change them in the 'MySqlDbType.' type it says that 'Index is outside the bounds of the array' and the error points to the code 'cmd.ExecuteNonQuery()'. I changed it from 'MySqlDbType.VarChar' to 'MySqlDbType.Date' and so on and when I put Int or Integer in it says that it isn't a part of the MySqlDbType.
Imports MySql.Data.MySqlClient
Imports System.IO
Public Class Form1
Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
Dim filename As String = "C:\Users\user\desktop\trial.txt"
Dim query As String = "INSERT INTO swipe_table VALUES (#Emp_id, #Date, #Time)"
Dim allLines As String() = File.ReadAllLines(filename)
Using con As MySqlConnection = New MySqlConnection("Data Source=localhost;Database=cph;User ID=root;Password=;")
con.Open()
Using cmd As New MySql.Data.MySqlClient.MySqlCommand(query, con)
For Each line In allLines
Dim emp_id, dt, time As String
emp_id = line.Substring(0, 4)
dt = line.Substring(5, 10)
time = line.Substring(16, 4)
cmd.Parameters.Clear()
Dim pEmp_id As New MySql.Data.MySqlClient.MySqlParameter("#Emp_id", MySqlDbType.VarChar)
pEmp_id.Value = emp_id
cmd.Parameters.Add(pEmp_id)
Dim pDate As New MySql.Data.MySqlClient.MySqlParameter("#Date", MySqlDbType.VarChar)
pDate.Value = dt
cmd.Parameters.Add(pDate)
Dim pTime As New MySql.Data.MySqlClient.MySqlParameter("#Time", MySqlDbType.VarChar)
pTime.Value = time
cmd.Parameters.Add(pTime)
cmd.ExecuteNonQuery()
Next
MsgBox("All records were inserted successfully")
con.Close()
End Using
End Using
End Sub
End Class
If you're storing true dates in your database then, regardless of the database, you need to convert your text into DateTime values in VB.NET. Your ADO.NET provider will then worry about the rest. To convert a String representation of a date into a DateTime you would use one of the Parse, TryParse, ParseExact and TryParseExact methods of the DateTime type.
By the way, your date is apparently in MM/dd/yyyy format, not mm-dd-yyyy.
I got it already, I just added a DateTime.ParseExact
Imports MySql.Data.MySqlClient
Imports System.IO
Imports System.Globalization
Public Class Form1
Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles `enter MyBase.Load
Dim filename As String = "C:\Users\user\desktop\trial.txt"
Dim query As String = "INSERT INTO swipe_table VALUES (#Emp_id, #Date, #Time)"
Dim allLines As String() = File.ReadAllLines(filename)
Using con As MySqlConnection = New MySqlConnection("Data Source=localhost;Database=cph;User ID=root;Password=;")
con.Open()
Using cmd As New MySql.Data.MySqlClient.MySqlCommand(query, con)
For Each line In allLines
Dim emp_id, time As String
Dim dt As Date
dt = DateTime.ParseExact("2012-05-20", "yyyy-MM-dd", CultureInfo.InvariantCulture)
emp_id = line.Substring(0, 4)
dt = line.Substring(5, 10)
time = line.Substring(16, 5)
cmd.Parameters.Clear()
Dim pEmp_id As New MySql.Data.MySqlClient.MySqlParameter("#Emp_id", MySqlDbType.VarChar)
pEmp_id.Value = emp_id
cmd.Parameters.Add(pEmp_id)
Dim pDate As New MySql.Data.MySqlClient.MySqlParameter("#Date", MySqlDbType.Date)
pDate.Value = dt
cmd.Parameters.Add(pDate)
Dim pTime As New MySql.Data.MySqlClient.MySqlParameter("#Time", MySqlDbType.VarChar)
pTime.Value = time
cmd.Parameters.Add(pTime)
cmd.ExecuteNonQuery()
Next
MsgBox("All records were inserted successfully")
con.Close()
End Using
End Using
End Sub
End Class
I'm trying to make a Microsoft Access query depend on a value in another form's textbox.
This is the criteria, as it is now. Basically, any date between April 1st 2014, and March 31st 2015. This works well.
>=#2014-04-01# And <#2015-04-01#
I'd like to have a textbox with the year (with the current example 2014), and make the query criteria (2014, 2014+1) depend on this value.
I've tried to split the above syntax, then concatenate in the criteria, as such:
">=#" & "2014" & "-04-01# And <#" & "2015" & "-04-01#"
And I get an error "Data types in the criterion expression are incompatible".
1. Is it possible to concatenate in the query criteria?
I have also tried the SQL CONCAT(string1,string2,string3,..), to no avail.
If this is possible, then I guess I can use [Forms]![Form1].[Textbox1] and ([Forms]![Form1].[Textbox1] + 1) to replace the years.
If this is not possible...
2. Is there a better way to make the query criteria dynamic?
I tried to make the following solution work by creating a module with similar code:
Private m_varQueryParam As Variant
Public Function SetQueryParam(ByVal sValue as Variant)
m_varQueryParam = sValue
End Function
Public Function GetQueryParam() As Variant
GetQueryParam = m_varQueryParam
End Function
Query:
SELECT * FROM tblYourTable WHERE [FilterField] = GetQueryParam()
The VBA Code to launch the query will look like this.
SetQueryParam "your value here"
DoCmd.OpenQuery "qryYourQueryHere"
But I simply do not understand how to get this to work.
EDIT: I created a simple access database, to try to get this to work.
Textbox1, default value =Date()
bSave, button
tDateInfo, table: date (date/time), info (text) with random dates and info.
Query1:
SELECT tDateInfo.date, tDateInfo.info
FROM tDateInfo
WHERE (((tDateInfo.date)=GetQueryParam()));
Here's the form's vba code
Option Compare Database
Private Sub bSave_Click()
sValue = Me.TextBox1.Value
SetQueryParam (sValue)
End Sub
Here's the modules vba code
Option Compare Database
Option Explicit
'is this necessary?
Private m_varQueryParam As Variant
Public Function SetQueryParam(ByVal sValue As Variant)
m_varQueryParam = sValue
End Function
Public Function GetQueryParam() As Variant
GetQueryParam = m_varQueryParam
End Function
And the query criteria is GetQueryParam()
Thank you for your help.
Handling parameters and form fields is a little tricky with VBA. I created a simple table similar to yours as follows:
CREATE TABLE DateCalc (
ID AutoNumber,
FilterField DateTime
)
The following code will return your desired results:
Sub testthis()
Dim db As dao.database
Set db = CurrentDb ' use current database
Dim qd As dao.QueryDef
Set qd = db.CreateQueryDef("") ' create anaonymous querydef
' the SQL statement correctly concatenates the parameter (Useyear) and mm/dd strings
qd.sql = "SELECT * FROM DateCalc WHERE [FilterField] >= [UseYear]" & "-04-01 And [FilterField] < [UseYear]+1" & "-04-01"
qd!UseYear = Forms!DateCalc!txtYear ' set the value of se year from the Form WHICH MUST BE OPEN
' AND the TetBox filled with the year you desire - 2014 for this example.
Dim rs As dao.recordSet
Set rs = qd.OpenRecordset
MsgBox "ID=" & rs(0) & ", Date=" & rs(1)
End Sub
NEW VERSION
Sorry, there were a couple of date formatting problems with the first solution that the following code resolves. There are a number of other reasons for the error, so be sure the FormName is "DateCalc" and the TextBox is named "txtYear".
You should be able to generalize the following code for all your queries (do those actually work?). I pass the TableName in now as an example:
Sub DateFilter(TableName As String)
Dim db As dao.database
Set db = CurrentDb ' use current database
Dim qd As dao.QueryDef
Set qd = db.CreateQueryDef("") ' create anaonymous querydef
' the SQL statement correctly concatenates the parameter (Useyear) and mm/dd strings
Dim UseYear As Integer
UseYear = Forms!DateCalc!txtYear
Dim BegDate As Date
BegDate = CDate(UseYear & "-04-01")
Dim EndDate As Date
EndDate = CDate((UseYear + 1) & "-04-01")
qd.sql = "SELECT * FROM " & TableName & " WHERE [FilterField] >= [UseBegDate] And [FilterField] < [UseEndDate]"
qd!UseBegDate = BegDate
qd!UseEndDate = EndDate
Dim rs As dao.recordSet
Set rs = qd.OpenRecordset
Do While Not rs.EOF
MsgBox "ID=" & rs(0) & ", Date=" & rs(1)
rs.MoveNext
Loop
End Sub
I think I found a solution.
The following code defines the SQL as I require it, and changes the SQL for the Access query.
It's not ideal, because it requires me to rewrite all the SQL for the queries, but it works.
Sub ChangeQuery()
Dim Year, sqlTwo, StartDate, EndDate As String
Year = Me.txtYear.Value
StartDate = "4/1/" & Year
EndDate = "4/1/" & (Year + 1)
sqlTwo = "SELECT DateCalc.ID, DateCalc.FilterField FROM DateCalc WHERE (((DateCalc.FilterField)>=#" & StartDate & "# And DateCalc.FilterField<#" & EndDate & "#));"
tbTest.Value = sqlTwo
Dim oDB As Database
Dim oQuery As QueryDef
Set oDB = CurrentDb
Set oQuery = oDB.QueryDefs("Query1")
oQuery.SQL = sqlTwo
Set oQuery = Nothing
Set oDB = Nothing
End Sub
Private Sub Button_Click()
ChangeQuery
End Sub