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.
Related
I'm using a VBA code in excel to pick some data and insert it into an Access DB. I need this for several tables.
The problem is: For some of those tables, I get an error like: "INSERT INTO syntax error". But, if I get the string the code generates and uses for inserting, and use it in SQL mode form Access, the query works just fine. So that doesn't make any sense. Here is a piece of it:
For j = 6 To lastrow
SQLStr = "INSERT INTO TENSILE(REFERENCE, REF_ID, POSITION, RATIO, YSL0, YSL90, YSL180, YSL270, YST0, YST90, YST180, YST270, UTSL0, UTSL90, UTSL180, UTSL270, UTST0, UTST90, UTST180, UTST270, EL0, EL90, EL180, EL270, ET0, ET90, ET180, ET270, ARL0, ARL90, ARL180, ARL270, ART0, ART90, ART180, ART270) SELECT '" & ws3.Cells(j, 1) & "', REF.ID,'" & ws3.Cells(j, 60).Value & "'"
For i = 61 To 93
SQLStr = SQLStr & "," & ws3.Cells(j, i).Value
Next i
SQLStr = SQLStr & " FROM REF WHERE REF.REFERENCE LIKE '" & ws3.Cells(j, 1) & "'"
ws3.Cells(7, 3).Value = SQLStr
MsgBox (SQLStr)
'rs.Open SQLStr, con, adOpenStatic, adLockOptimistic 'Opening the query
Next j
it's important to notice that this same structure is used for other tables and works normaly, like in:
For j = 6 To lastrow
SQLStr = "INSERT INTO METALOGRAPHY(REFERENCE, REF_ID, AUSTGRAINSIZE) SELECT '" & ws3.Cells(j, 1) & "',REF.ID ," & ws3.Cells(j, 18).Value & " FROM REF WHERE REF.REFERENCE LIKE '" & ws3.Cells(j, 1) & "'"
'MsgBox (SQLStr)
'ws3.Cells(2, 3).Value = SQLStr
rs.Open SQLStr, con, adOpenStatic, adLockOptimistic 'Opening the query
Next j
What is going wrong?
Have you considered changing how you are linked to the Access DB so that you could use a statement like:
db.execute SQLStr
This should solve your problem
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.
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
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 "',");"
When I select the value from the combo box, related value should appear in the text box
ComboBox code.
cmd.CommandText = "select distinct PERSONID from T_PERSON"
Set rs = cmd.Execute
While Not rs.EOF
If Not IsNull(rs("PersonID")) Then
txtno.AddItem rs("PersonID")
End If
rs.MoveNext
Wend
In comboBox list of ID is displaying, when I select the particular person id, Name should display in text box related to the personid
Text Box
cmd.CommandText = "select distinct Name from T_Person where personid = '" & txtno & " '"
Set rs = cmd.Execute
While Not rs.EOF
If Not IsNull(rs("Name")) Then
txtName.Text = rs("Name")
rs.MoveNext
End If
Wend
I put the above code in Form_Load Event, Nothing displaying in Text Box.
What wrong in my code.
Need VB6 code Help
You would want the 2nd block of code in the the click event for the combobox.
Edit
There looks like another couple of issues in your code at this line:
cmd.CommandText = "select distinct Name from T_Person where personid = '" & txtno & " '"
2 Issues:
You are passing in the control itself as the person ID, not the selected value.
You have an extra space in your query after the person ID
You should change that line to be:
cmd.CommandText = "select distinct Name from T_Person where personid = '" & txtno.SelectedItem.Text & "'"
Why not have the combobox display the name and hold the personID as it's item data?
cmd.CommandText = "select distinct PERSONID, Name from T_PERSON WHERE PersonID IS NOT NULL"
Set rs = cmd.Execute
While Not rs.EOF
combo.AddItem rs("Name").value
combo.ItemData(combo.NewIndex) = rs("PERSONID").value
rs.MoveNext
Wend
Then, if you need the PersonID for the selected name you can just grab combo.ItemData(combo.ListIndex).