i hope you can help me. Fist of all, sorry if my English is annoying, i'm not a native speaker.
I'm getting this error and i can't see what i'm doing wrong. I have a program that fills a local MySQL DB with data from another program that uses an OLEB DB.
So it compares the tables and upload new data on demand. But i'm getting this error with only one table using the same Sub that i used with other tables.
Unknown column 'lpedidos.serie' in 'field list'
The problem is that 'lpedidos.serie' exists indeed. So here is the code of the sub, please don't laugh, i know that maybe is extremely inefficient, but i'm just a noob.
Public Sub notIndexedTables(table As DataTable, table2 As DataTable, tableNA As String)
Dim temptable As DataTable
temptable = table.Clone
Dim tablename As String = temptable.TableName
Dim myAdapter As MySql.Data.MySqlClient.MySqlDataAdapter
Dim SQL As String
Dim newconn As New MySql.Data.MySqlClient.MySqlConnection
newconn = mysqlConnection()
newconn.Open()
SQL = "TRUNCATE " & tableNA
myAdapter = New MySql.Data.MySqlClient.MySqlDataAdapter()
Dim command As MySql.Data.MySqlClient.MySqlCommand
command = New MySql.Data.MySqlClient.MySqlCommand(SQL, newconn)
myAdapter.DeleteCommand = command
myAdapter.DeleteCommand.ExecuteNonQuery()
For Each row As DataRow In table.Rows()
Dim columnNumber As Int32 = row.ItemArray.Count
Dim i As Integer = 0
Dim s1 As String = "("
For Each columna In row.ItemArray
i = i + 1
If i = columnNumber Then
s1 = s1 + CStr(table2.Columns.Item(i - 1).ColumnName) & ")"
Else
s1 = s1 & CStr(table2.Columns.Item(i - 1).ColumnName) & ", "
End If
Next
Dim s2 As String = "("
i = 0
For i = 0 To (columnNumber - 2)
s2 = s2 & "'" & CStr(row.Item(i)) & "', "
Next
s2 = s2 & "'" & CStr(row.Item(columnNumber - 1)) & "')"
SQL = "INSERT INTO " & tableNA & " " & s1 & " VALUES " & s2
myAdapter = New MySql.Data.MySqlClient.MySqlDataAdapter()
' myCommand = New MySql.Data.MySqlClient.MySqlCommandBuilder(myAdapter)
command = New MySql.Data.MySqlClient.MySqlCommand(SQL, newconn)
myAdapter.InsertCommand = command
myAdapter.InsertCommand.ExecuteNonQuery()
Next
newconn.Close()
newconn.Dispose()
End Sub
Basically it takes the MySQL table (tableNA), truncates it (this procedure is for tables with no index, there is other procedure for tables with unique index) and fills it with the data from the OLEB table (table) and takes the column names from the temporal copy of the MySQL table (table2) (maybe there is no need to use the table2 in this case... but anyway).
Here is the exception and the value that SQL string takes when the exception is thrown.
And here is a screenshot of the table structure in phpMyAdmin.
When you declare the New MySqlConnection you need to put the connection string in there and specify the database name. Can you show your connection string?
Dim myConnection As New MySqlConnection(myConnString)
myConnection.Open()
If that doesn't solve the problem, then try another column name and make sure it isn't a reserved keyword.
Related
I will explain this as much as possible.
I have a project which need to show the names from database to textboxes. I have 2 datetimepicker for searching between dates and 5 textboxes to show the names in mysql database. for example I select the from start date 2018/12/07 and end date 2019/01/07 in the datagridview it will show all the rows and columns in-between dates. However, I need the names to show on my 5 textboxes. I don't have a code since I don't know where to begin with.
In mysqldatabase I have only id,name,dateofentry.
In my form :
datetimepicker1 = startdate
datetimepicker2 = enddate
button1 = generatebutton
textbox1 = nametxt1
textbox2 = nametxt2
textbox3 = nametxt3
textbox4 = nametxt4
textbox5 = nametxt5
Update when I use this:
mysqlconn.Open()
COMMAND.Connection = mysqlconn
COMMAND.CommandText = "Select name from table1 where dateofentry between '" & Format(Me.startdate.Value, "yyyy-MM-dd") & "' AND '" & Format(Me.endtime.Value, "yyyy-MM-dd") & "'"
Dim sqlresult1 As Object
sqlresult1 = COMMAND.ExecuteScalar
Dim str1 As String
str1 = sqlresult1
nametxt1.Text = str1
mysqlconn.Close()
The same name shows in each of my 5 textboxes
Thank you for answering this question.
Explanations and comments in-line.
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
'The Using block ensures that your database objects are closed and disposed
'even if there is an error
Dim dt As New DataTable
Using cn As New MySqlConnection("Your connection string")
'Pass the Select statement and the connection to the constructor of the command
Using cmd As New MySqlCommand("Select name from table1 where dateofentry between #Date1 AND #Date2;", cn)
'Use parameters
cmd.Parameters.Add("#Date1", MySqlDbType.Date).Value = DateTimePicker1.Value
cmd.Parameters.Add("#Date2", MySqlDbType.Date).Value = DateTimePicker2.Value
'open the connection at the last possible moment
cn.Open()
'Execute scalar only returns the first row, first column of the result set
dt.Load(cmd.ExecuteReader)
End Using
End Using
'Then a little link magic to dump the first column of the table
'to an array
Dim names() = (From row In dt.AsEnumerable()
Select row(0)).ToArray
'If there are less than 5 records returned this
'code will fail, Add a check for this and
'adjest your code accordingly
TextBox1.Text = names(0).ToString
TextBox2.Text = names(1).ToString
TextBox3.Text = names(2).ToString
TextBox4.Text = names(3).ToString
TextBox5.Text = names(4).ToString
End Sub
SELECT *
FROM `tblPerson`
WHERE (date_field BETWEEN '2018-12-30 14:15:55' AND '2019-01-06 10:15:55')
LIMIT 5;
text1.text = dt.Rows[0]["name"].ToString();
text2.text = dt.Rows[1]["name"].ToString();
text3.text = dt.Rows[2]["name"].ToString();
text4.text = dt.Rows[3]["name"].ToString();
text5.text = dt.Rows[4]["name"].ToString();
I am looking for any advice on how i can read a single column in excel that contains 500 user_id's and query a database to display results in a WPF application. A user can own or rent so the SQL would look like;
SELECT * FROM users WHERE own= 'user_id' or rent= 'user_id'
This is fine for one user but i want to read each user_id and concatenate it to the SQL statement to pull out all results from the database. Any one have any easy way of doing this?
Replace the range as necessary, credit to brettdj on the join - Simple VBA array join not working
Sub test()
Dim strQuery As String
Dim strVals As String
Dim rngTarget As Range
Set rntTarget = Range("A1:A7")
Dim varArr
Dim lngRow As Long
Dim myArray()
varArr = rntTarget.Value2
ReDim myArray(1 To UBound(varArr, 1))
For lngRow = 1 To UBound(varArr, 1)
myArray(lngRow) = varArr(lngRow, 1)
Next
strVals = "('" & Join$(myArray, "','") & "') "
strQuery = "SELECT * FROM users WHERE own in " _
& strVals & "or rent in " & strVals
End Sub
So basically I'm trying to write the below code to the database and I have the primary key as an Int and it was autogen but when writing to the database it didnt allow me to do it kept telling me that I wasn't allowed to enter a null value (because the code is obviously not writing to the primary key field) so I used the line
cmd.Parameters.Add("#EventID", SqlDbType.Int).Value = 3
But the problem is I have to change the value each time I want to test a new record i.e. 1,2,3,4 and so on. I was wondering is there a line of code I can put in to make it create a value by adding +1 each time so I don't need to go into the code and enter a new number each time. Below is the full code writing to the database so you can see a better view of it
Dim Con As SqlConnection
Dim cmd As SqlCommand
Dim recordsAffected As String
Dim cmdstring As String = "INSERT [Event Table](EventID, EventTypeID, EventName, VenueName, NumberOfGuests, Date, ClientAddress, WeddingName, BuildingAddress) Values(#EventID, #EventTypeID, #EventName, #VenueName, #NumberOfGuests, #Date, #ClientAddress, #WeddingName, #BuildingAddress)"
Con = New SqlConnection("Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\YellowDoor.mdf;Integrated Security=True;User Instance=True")
cmd = New SqlCommand(cmdstring, Con)
cmd.Parameters.Add("#EventID", SqlDbType.Int).Value = 3
cmd.Parameters.Add("#EventTypeID", SqlDbType.Text).Value = EventTypeDD.SelectedValue
cmd.Parameters.Add("#EventName", SqlDbType.Text).Value = EventNametxt.Text
cmd.Parameters.Add("#VenueName", SqlDbType.Text).Value = VenueLoDD.SelectedValue
cmd.Parameters.Add("#NumberOfGuests", SqlDbType.Int).Value = CInt(NumOfGtxt.Text)
cmd.Parameters.Add("#Date", SqlDbType.Int).Value = CInt(DateTxt.Text)
cmd.Parameters.Add("#ClientAddress", SqlDbType.Text).Value = txtAddress.Text
cmd.Parameters.Add("#WeddingName", SqlDbType.Text).Value = txtWedding.Text
cmd.Parameters.Add("#BuildingAddress", SqlDbType.Text).Value = txtBAddress.Text
Con.Open()
recordsAffected = cmd.ExecuteNonQuery
Con.Close()
If your EventID is an IDENTITY column, you should never try to set a value for it.
Just ignore that field both as parameter or inside the INSERT command.
And you can retrieve the value assigned by the database engine to your field in this way
Dim Con As SqlConnection
Dim cmd As SqlCommand
Dim cmdstring As String = "INSERT [Event Table] " & _
"(EventTypeID, EventName, VenueName, NumberOfGuests, [Date], ClientAddress, " & _
"WeddingName, BuildingAddress) Values(#EventTypeID, #EventName, #VenueName, " & _
"#NumberOfGuests, #Date, #ClientAddress, #WeddingName, #BuildingAddress); " & _
"SELECT SCOPE_IDENTITY()"
Using Con = New SqlConnection(".....")
Using cmd = New SqlCommand(cmdstring, Con)
cmd.Parameters.Add("#EventTypeID", SqlDbType.Text).Value = EventTypeDD.SelectedValue
.....
Con.Open()
Dim result = cmd.ExecuteScalar()
if result IsNot Nothing Then
Dim newEventID = Convert.ToInt32(result)
....
End If
End Using
End Using
With this code you don't pass anything for the EventID field but you add a second command text to your query. This second command will return the last value generated for an IDENTITY column by the database for your connection. This double command (A.K.A. batch commands) is executed using ExecuteScalar because we are interested in the single value returned by the SELECT SCOPE_IDENTIY()
Notice also that DATE is a reserved word in T-SQL so it is possible to use it as name of a column only if you enclose it in square brackets
I am an old Foxpro programmer and I use to use arrays to post variable fields.
What I am trying to do is I have 15 date fields in the new table I designed.
In my query I have individual records with one date for activity.
I want to compile the 15 different dates for a each Client_id into one record with 15 dates but I can't seem to reference the table data as an array.
I have tried a couple different methods of defining the array but nothing seems to work.
Here is my code that I have. In my table I have 15 date fields named Mail_date1, Mail_date2, Mail_date3, etc.
I tried first defining it just as an array but did not like it; my code always fails when I try to reference the date field in the result table rs2!mdate2 = memdate(intcounter)
How can I reference my result table output fields as an array?
Do I have to put a whole bunch of if statements to load my results?
Seems like a waste.... should be able to load them as an array.
I am a new Access 2007 VBA programmer.
Dim db As DAO.Database
Set db = CurrentDb
Dim rs1 As DAO.Recordset
Dim rs2 As DAO.Recordset
Dim FinTotal, intcounter As Integer
Dim FinMPU, FinVersion As String
Dim mail_date(1 To 15) As Date
Dim memdate(1 To 15) As Date
Dim mdate2 As String
Set rs1 = db.OpenRecordset( _
"SELECT NewFile.MPU_ID, " & _
" NewFile.MAIL_DATE," & _
" NewFile.TOTAL, " & _
" Freight.Version " &_
"FROM Freight " & _
" LEFT JOIN NewFile ON Freight.[MPU ID] = NewFile.MPU_ID " & _
"ORDER BY NewFile.MPU_ID, NewFile.MAIL_DATE")
Set rs2 = db.OpenRecordset("Final")
DoCmd.RunSQL "DELETE Final.* FROM Final;"
intcounter = 1
memdate(intcounter) = rs1!mail_date
FinMPU = rs1!mpu_ID
FinTotal = rs1!total
FinVersion = rs1!Version
rs1.MoveNext
On Error GoTo Error_MayCauseAnError
Do While Not rs1.EOF
Do While Not rs1.EOF _
And memdate(intcounter) <> rs1!mail_date _
And FinMPU = rs1!mpu_ID
intcounter = intcounter + 1
memdate(intcounter) = rs1!mail_date
FinTotal = FinTotal + rs1!total
FinVersion = rs1!Version
FinMPU = rs1!mpu_ID
rs1.MoveNext
Loop
If FinMPU <> rs1!mpu_ID Then
rs2.AddNew
mdate2 = "mail_date" & CStr(intcounter)
rs2!mdate2 = memdate(intcounter)
rs2!total = FinTotal
rs2!mpu_ID = FinMPU
rs2!Version = FinVersion
rs2.Update
FinTotal = rs1!total
FinVersion = rs1!Version
FinMPU = rs1!mpu_ID
intcounter = 1
memdate(intcounter) = rs1!mail_date
End If
rs1.MoveNext
Loop
first, if you expect and answer, you should really spend more time on properly formatting your explanation and your code...
Now, for some remarks and possible answer to the question:
You should DELETE FROM Final before you open that table in a recordset.
You should be explicit about the type of recordset you are opening:
' Open as Read-only '
Set rs1 = db.OpenRecordSet("...", dbOpenSnapshot)
' Open as Read/Write '
Set rs1 = db.OpenRecordSet("...", dbOpenDynaset)
You should Dim memdate(1 To 15) As Variant instead of Date as the Date datatype cannot be Null, and since you are pulling data from a LEFT JOIN, it's possible that the returned values could be Null if there are no corresponding data to Freight in the table Newfile.
That On Error GoTo Error_MayCauseAnError should probably not be there.
Use On Error Goto only to catch errors you can't deal with at all.
Using that here will only hide errors in your code. With some proper checks statements you should not even need the On Error Goto...
It looks like your first internal loop is trying to skip some records.
However, when that loop breaks, it could be because it reached EOF, and you never test for that in the code that follows the loop.
You never test if your intcounter goes beyond the 15 allocated dates.
Are you absolutely sure that you can never have more than 15 records?
You do not say which error message you get exactly. That could be useful to help determine the kind of issue at hand.
Instead of
mdate2 = "mail_date" & CStr(intcounter)
rs2!mdate2 = memdate(intcounter)
Use
rs2.Fields("mail_date" & intcounter).Value = memdate(intcounter)
the ! syntax of DAO really only is a shorthand for the longer rs.Fields("name") form.
The goal is to join an Access table with matching data from a SQL Server table. I would do this using linked tables in Access but I'm running into Access' BigInt problem (I would have a view created to cast BigInt as Int but that isn't an option right now).
So I've been trying to create two recordsets and join them in VBA/ADO. The left side of the join would be the Access table with Season and WeekNum and the right side of the join would be the SQL Server table with Season and Weeknum and other data. This works fine until I try to create a third recordset that is the result of the join (in this example, I haven't tried to do a join, just the first part of the join by selecting from the Access recordset). I'm getting a Type Mismatch error on the line when I do Set ObjRecordset3 = "SELECT * FROM " & Access_Recordset '.
Is it even possible to join two recordsets? If so, how is this done?
Function Join()
Dim SQL_Server_Connection As ADODB.Connection
Set SQL_Server_Connection = New ADODB.Connection
Dim SQL_Server_Query As String
Dim SQL_Server_Recordset As New ADODB.Recordset
Dim Access_Recordset As New ADODB.Recordset
Dim ObjConnection As ADODB.Connection
Set ObjConnection = CreateObject("ADODB.Connection")
Dim ObjRecordset3 As New ADODB.Recordset
' Get data from Bump Table 3:
Access_Recordset.Open "SELECT * FROM [Bump Table 3]", CurrentProject.Connection
' Open connection to SQL Server:
SQL_Server_Connection_String = "DSN=MySQLServer"
SQL_Server_Connection.Open SQL_Server_Connection_String
' Define the SQL Server query:
SQL_Server_Query = "SELECT Season, WeekNum FROM TE"
' Populate the SQL_Server_Recordset:
SQL_Server_Recordset.Open SQL_Server_Query, SQL_Server_Connection, adOpenDynamic, adLockOptimistic
'Join Access_Recordset (Table: Bump Table 3) to SQL_Server_Recordset (Table: TE)
Set ObjRecordset3 = "SELECT * FROM " & Access_Recordset ' Type Mismatch error on this line
Access_Recordset.Close
Set Access_Recordset = Nothing
SQL_Server_Recordset.Close
Set SQL_Server_Recordset = Nothing
SQL_Server_Connection.Close
End Function
* UPDATE *
I figured out how to get to my ultimate goal which was to get data about a list of account numbers in an Access table from SQL Server based on the account number field which is common to both tables. Realizing that I can create a persistent temp table on SQL Server, I used a combination of DAO and ADO to get the values from the Access table and create a temp table. All I had to do then is run the pass-through query which references the temp table. The only odd thing (which is not a problem at this point) is if I create the temp table and run the pass-through query in VBA, this setup works. But if I create the temp table in VBA and double-click on the pass-through query, Access says that the temp table can't be found. Anyway, here's the code:
Public Sub Insert_Into_Access_From_ADO_Recordset_Using_PTQ_Simpler()
Dim dbs As DAO.Database
Set dbs = CurrentDb()
Dim cnn As ADODB.Connection
Set cnn = New ADODB.Connection
Dim rst As ADODB.Recordset
'Open SQL Server
Dim str_cnn As String
str_cnn = "MYDSN"
cnn.Open str_cnn
' Drop the temp table:
Dim str_SQL_Drop_Temp_Table As String
str_SQL_Drop_Temp_Table = "IF OBJECT_ID('tempdb..##BumpData','U') IS NOT NULL "
str_SQL_Drop_Temp_Table = str_SQL_Drop_Temp_Table & " DROP TABLE ##BumpData "
cnn.Execute str_SQL_Drop_Temp_Table
' Create the temp table:
Dim str_SQL_Create_Temp_Table As String
str_SQL_Create_Temp_Table = " CREATE TABLE ##BumpData "
str_SQL_Create_Temp_Table = str_SQL_Create_Temp_Table & " " & "("
str_SQL_Create_Temp_Table = str_SQL_Create_Temp_Table & " " & " ID INT "
str_SQL_Create_Temp_Table = str_SQL_Create_Temp_Table & " " & " , AccountNumber VARCHAR(Max)"
str_SQL_Create_Temp_Table = str_SQL_Create_Temp_Table & " " & ")"
cnn.Execute str_SQL_Create_Temp_Table
' Insert values from the Access table into the temp table
' by looping through the Access table as a recordset:
Dim rst_DAO As DAO.Recordset
Set rst_DAO = dbs.OpenRecordset("Bump Data")
Dim str_SQL_Insert As String
rst_DAO.MoveFirst
With rst_DAO
Do While Not rst_DAO.EOF
'str_Loan_Number_List = str_Loan_Number_List & "'" & Trim(rst![Loan Number]) & "'" & ","
str_SQL_Insert = " INSERT INTO ##BumpData VALUES (" & rst_DAO![ID] & ",'" & Trim(rst_DAO![Loan Number]) & "') "
cnn.Execute str_SQL_Insert
.MoveNext
Loop
End With
' Run the pass-thru query which joins to the temp table:
DoCmd.SetWarnings False
DoCmd.RunSQL "SELECT * INTO [Bump Results] FROM [Bump PTQ]"
DoCmd.SetWarnings True
End Sub
You reported this line triggers the error:
Set ObjRecordset3 = "SELECT * FROM " & Access_Recordset
The right side of the = sign attempts to concatenate a string with an ADODB.Recordset object. That is probably the immediate cause of the compile error. However, that's not the only problem with that line. Set <recordset object> = "any string value" will not work. And finally, Access SQL does not support FROM <recordset object> for any type of recordset object (ADO or DAO).
I think you should look for a simpler approach. In following query, dbo_BigIntTable is an ODBC link to a SQL Server table. It includes a field, bigint_fld, whose SQL Server data type is BigInt. However, Access sees that field as Text type. Therefore I can join it with the string equivalent of a Long Integer field (tblFoo.id).
SELECT tblFoo.id, dbo_BigIntTable.bigint_fld
FROM
tblFoo
INNER JOIN dbo_BigIntTable
ON CStr(tblFoo.id) = dbo_BigIntTable.bigint_fld;
The Access query designer complained it can't display that join in Design View, but I was able create the join from SQL View and it worked fine.