Visual Basic 2010 Inserting current date to database - visual-studio-2010

I can't seem to add the current time to my database. I've tried the following:
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
provider = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source ="
dataFile = "F:\daniel\Sample Program\database\attendance.accdb"
connString = provider & dataFile
myConnection.ConnectionString = connString
myConnection.Open()
Dim Timein As Date
Timein = Now()
Timein = "insert into timesheet (time1) values (NOW())"
Dim cmd As OleDbCommand = New OleDbCommand(Timein, myConnection)
cmd.Parameters.Add(New OleDbParameter("time1", CType(Button1.Text, Date)))
Try
cmd.ExecuteNonQuery()
cmd.Dispose()
myConnection.Close()
Catch ex As Exception
MsgBox(ex.Message)
myConnection.Close()
End Try
End Sub

Try this:
Dim Timein As Date
Timein = Now()
Dim sqlText as String
sqlText = "insert into timesheet (time1) values (timeParam)"
Dim cmd As OleDbCommand = New OleDbCommand(sqlText, myConnection)
cmd.Parameters.Add(New OleDbParameter("timeParam", Timein))
Disclaimer: this was done from memory and not tested.
Edited to add: how to insert two values at once:
Dim sqlText as String
sqlText = "insert into timesheet (time1, time2) values(timeParam1, timeParam2)"
Dim cmd as OleDbCommand = New OleDbCommand(sqlText, myConnection)
cmd.Parameters.Add(New OleDbParameter("timeParam1", Timein))
cmd.Parameters.Add(New OleDbParameter("timeParam2", Timeout))
If what you need to do is come back later and update your first timesheet row with a second value, that will require an Update statement. Post another question asking about that.
To modify how the timesheet value is displayed, you can use the String.Format() function:
txtTime1.Text = String.Format("{0:yyyy-MM-dd hh:mm:ss}", Timein)
That long string used as the first parameter is what's called a custom format string: you can read about them at Custom Date and Time Format Strings.

if u want current date and Time (example:27/12/2019 12:00 )
sql="INSERT INTO TableName (id, date) VALUES(" 1 ",'" NOW "',");"
if u want current date only (example:27/12/2019 )
sql="INSERT INTO TableName (id, date) VALUES(" 1 ",'" TODAY "',");"

Related

How to run an insert query on VB 6.0?

I am New to Visual Basic 6.0 and I don't know how to code SQL queries, specially Insert Into
I have 1 database with 2 tables(tblNames, tblRemarks)..
in tblNames the fields are:
ID, LastName, FirstName, MidName, DateHired, Position, Department
in tblRemarks the fields are:
ID, FullName, txtDate, Remarks, DateHired, Position
What I am doing is like this:
SQL = "SELECT ID, LastName, FirstName, MidName, DateHired, Position FROM tblNames"
SQL2 = "SELECT * fROM tblRemarks"
and then on my form I have a DTPicker1 and Command1
I want to get all the records in tblNames and put it on tblRemarks, but also get the date from DTPicker1 and in Fields Remarks, the word "HOLIDAY".
What I'm doing is like this: om my Module I have this code:
Option Explicit
Public conn As New ADODB.Connection
Public RS As New ADODB.Recordset
Public cmd As New ADODB.Command
Public SQL As String
Public SQL2 As String
Public Sub connectDB()
conn.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & App.Path & "\Database.accdb;User ID=admin;Persist Security Info=False;JET OLEDB:Database Password=qqqq"
conn.Open
With RS
.ActiveConnection = conn
.Open SQL, conn, 3, 3
End With
End Sub
Public Sub connOpen()
conn.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & App.Path & "\Database.accdb;User ID=admin;Persist Security Info=False;JET OLEDB:Database Password=qqqq"
conn.Open
With cmd
.ActiveConnection = conn
.CommandType = adCmdText
.CommandText = SQL
Set RS = .Execute
End With
End Sub
Then I just call that in my forms
my problem is this, I have 2 SQL queries, how can I connect these 2 SQL in my connection? I researched it, and found out I can do 1 QUERY by using INSERT.
I tried, but I cannot make it work. How can I achieve this? I am very new to VB6. Would it be like this?
SQL = "INSERT ID, LastName, FirstName, MidName, DateHired, Position FROM tblNames" _
& "INTO tblRemarks, #" & DatePick & "# as txtDate, 'HOLIDAY' as Remarks"
Totally untested but perhaps you can try the following
conn.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & App.Path & "\Database.accdb;User ID=admin;Persist Security Info=False;JET OLEDB:Database Password=qqqq"
conn.Open
SQL = "INSERT INTO tblRemarks " & _
"(FullName, txtDate, Remarks, DateHired, Position) " & _
"SELECT CONCAT_WS(' ', FirstName, MidName, LastName), ?, 'HOLIDAY', DateHired, Position " & _
"FROM tblNames"
With cmd
.ActiveConnection = conn
.CommandType = adCmdText
.CommandText = SQL
.Parameters.Append .CreateParameter(, adVarWChar, adParamInput, 100, DatePick)
.Execute
End With
Replace 100 with the width of your txtDate column.

DataGrid in VB6

I am working on a VB6 project that uses a MS Access database. I want to display the value of a column in DataGrid using the following logic:
1 for a value of 1
2 for a value of 2
0 for other values
Can anyone help me?
You can add the logic directly into your SQL statement using IIF statement:
Select IIF(YourValue < 2, YourValue, 0) as NewValue, * FROM YourTable
This code loads records from a YourTable table (please update with your table name) and applies the logic your described to the YourValue field (if value is smaller than 2, return 0):
Dim objConnection As ADODB.Connection
Dim objRecordset As New ADODB.Recordset
Dim sSQLStatement As String
Set objConnection = New ADODB.Connection
Set objRecordset = New ADODB.Recordset
sSQLStatement = "Select IIF(YourValue < 2, YourValue, 0) as NewValue, * FROM YourTable"
objConnection.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + App.Path + "\YourDatabase.mdb"
objConnection.Open
objRecordset.CursorLocation = adUseClient
objRecordset.Open sSQLStatement, objConnection, adOpenStatic, adLockOptimistic
Set DataGrid1.DataSource = objRecordset
You can add this logic to more columns, you simply need to add extra IIF statments to your sSQLStatement string:
Select IIF(Value1 < 2, Value1, 0) as NewValue1, IIF(Value2 < 2, Value2, 0) as NewValue2, IIF(Value3 < 2, Value3, 0) as NewValue3 FROM YourTable

populate values in textbox if select combobox vb6

I am using VB 6.0 I have one form (Form1), 1 combobox (ComboBox1), and 1 textbox (TextBox1)I have one table (Salary) in my local database which was created within the project.In Table 'Salary' I only have Four columns (UserID - Primary Key, Salary Type, Salary Range)the table has multiple records in it.
What I need to find out is how do have get the textbox to populate with the corresponding columns for whatever is selected in the combobox. Any and all help would be appreciated.
Here is the code which i was used to link database with VB :
Private WithEvents cmdPopulate As CommandButton
Private WithEvents dcbDataCombo As DataCombo
Private Sub Form_Load()
Dim rs As ADODB.Recordset
Dim strConnect As String
Dim strSQL As String
strConnect = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\Mahmoud\Desktop\Project\Database.mdb;Persist Security Info=False"
strSQL = "Select Distinct * FROM Salary order by UserID asc" ' set ascending order
Set rs = New ADODB.Recordset
With rs
.CursorType = adOpenStatic
.LockType = adLockReadOnly
.Open Source:=strSQL, _
ActiveConnection:=strConnect, _
Options:=adCmdText
End With
Set DataCombo1.RowSource = rs
DataCombo1.ListField = "UserID"
DataCombo1.DataField = "UserID"
End Sub
You wrote:
ActiveConnection:=strConnect
but strConnect is a string, while ActiveConnection require a ADODB.Connection object, not a string. Moreover, the connection must be already Open:
Dim CN As ADODB.Connection
Set CN = New ADODB.Connection
CN.ConnectionString = strConnect
CN.Open
CN.CursorLocation = adUseClient
' for recordset:
rs.Open strSQL, CN, adOpenStatic, adLockReadOnly, adCmdText
I have updated my answer from just the click event to a complete example:
Option Explicit
Private WithEvents cmdPopulate As CommandButton
Private WithEvents dcbDataCombo As DataCombo
Private rs As ADODB.Recordset
Private Sub Form_Load()
Dim strConnect As String
Dim strSQL As String
Dim cn As ADODB.Connection
strConnect = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\Mahmoud\Desktop\Project\Database.mdb;Persist Security Info=False"
strSQL = "Select Distinct * FROM Salary order by UserID asc" ' set ascending order
Set cn = New ADODB.Connection
cn.ConnectionString = strConnect
cn.Open
cn.CursorLocation = adUseClient
Set rs = New ADODB.Recordset
rs.Open strSQL, cn, adOpenStatic, adLockReadOnly, adCmdText
Set DataCombo1.RowSource = rs
DataCombo1.ListField = "UserID"
DataCombo1.DataField = "UserID"
End Sub
Private Sub DataCombo1_Click(Area As Integer)
rs.MoveFirst
rs.Find "UserID = " & DataCombo1.Text
If Not (rs.BOF Or rs.EOF) Then TextBox1.Text = rs.Fields("SalaryType").Value
End Sub
If the field name SalaryType is not correct then fix as needed.

Fetching Column with table name alias is not working in VBA

I am trying to connect to Oracle table through VBA and fetching data. My situation is to reference one table multiple times to do pivot. But while running query via VBA it's throwing an error as I am fetching data through table alias: Below is a dummy code.
Sub Button1_Click()
Dim strDataSource, strUsername, strPassword, strConnectionString, strquery As String
Dim objADODBConnection, objADODBRecordset As Object
strDataSource = "xxxx"
strUsername = "xxxx"
strPassword = "xxxx"
strConnectionString = "Provider=MSDAORA;Data Source=" & strDataSource & ";Persist Security Info=True;Password=" & strPassword & ";User ID=" & strUsername
Set objADODBConnection = CreateObject("ADODB.Connection")
objADODBConnection.Open strConnectionString
Set objADODBRecordset = CreateObject("ADODB.Recordset")
strquery = "SELECT T1.Column1 FROM Table1 AS T1 WHERE Column2='XXXX' AND Column3='XXXX'"
Set objADODBRecordset = objADODBConnection.Execute(strquery)
MsgBox objADODBRecordset.Fields(0).Value
objADODBRecordset.Close
objADODBConnection.Close
Set objADODBRecordset = Nothing
Set objADODBConnection = Nothing
End Sub
The same query is running fine without table alias. Please suggest!!
FROM Table1 AS T1
You should remove 'AS' in from condition -
FROM Table1 T1

Only 1 row in recordset but all rows in table get updated

The query retrieves a single record as is confirmed by the recordcount but every single row in the table gets updated
I am using vb6 and ms ado 2.8
The Firebird version is 2.5.4.26856 (x64).
Firebird ODBC driver 2.0.3.154
The computer is windows 7 home edition 64 bit
Dim cn As New ADODB.Connection
Dim rs As New ADODB.Recordset
Dim cs As String
Dim dbPath As String
dbPath = "c:\Parkes\Parkes.fdb"
cs = "DRIVER={Firebird/Interbase(r) Driver}; DBNAME=localhost:" & dbPath & "; UID=SYSDBA; PWD=masterkey;"
cn.ConnectionString = cs
cn.Open
Dim sQuery As String
sQuery = "select memo from clients where clientID = 10021 "
rs.Open sQuery, cn, adOpenStatic, adLockOptimistic
If rs.BOF <> True Or rs.EOF <> True Then
'putting msgbox rs.recordcount here confirms only 1 record in recordset
rs.Movefirst
rs.Fields("memo") = "blah"
rs.Update
End If
Set rs = Nothing
Set cn = Nothing
If I alter the query slightly by also selecting a second column, the client surname then only rows with the same value in the surname column as that of of the row where the clientid is 10021 get edited.
sQuery = "select memo, surname from clients where clientID = 10021 "
I cannot understand how more than one row should be edited when the recordset contains only a single row
EDIT: Having read around the web a bit this is my understanding of what is happening.
It seems that the update method identifies which records to update based on the selected columns in the recordset.
So if you select fields a,b,c,d and are updating field a, it will only update records in the database whose values for a,b,c,d match those in the recordset.
The best way to ensure that you only update a single record is to include the primary key in the selected fields.
So if I had written my query as in the line below, only a single record would have been updated because the clientID column contains unique values.
sQuery = "select memo, clientID from clients where clientID = 10021 "
It makes sense thinking about it but the way I wrote the query originally seems to work fine, in my experience, with other databases or am I wrong?
I tested your code everything was fine and only update one row. I only want to suggest you a simple way to check whether record exist or not. that could be like this:
if rs.rows.count > 0 then
' no need to move recordset to first by default its on the first row
end if

Resources