How to copy records from one table to another database table with different connection string? - sql

I have two(2) MS Access databases with different connections in different location. Deleting records from the table of the first database is working but inserting new records that was copied from the table of the second database is not working. The table of the first database remains blank. What happened was it was inserted the new records to the table of the second database, that's why the second database have many records because it copied and inserted to itself. What I want is that the copied records from second database will be pasted/inserted to the first database.
SQLStr1 is the location string of the first database
SQLStr2 is the location string of the second databas
Dim conn As OleDbConnection
Dim conn2 As OleDbConnection
Dim cmd As OleDbCommand
Dim cmd2 As OleDbCommand
Dim SQLStr1 As String
Dim SQLStr2 As String
conn = New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=psipop.accdb;Jet OLEDB:Database Password=cscfo13poppsi;")
'I used 'psipop' because the database is located the same with the application.
SQLStr1 = "DELETE * FROM pop 'psipop'"
conn.Open()
cmd = New OleDbCommand(SQLStr1, conn)
cmd.ExecuteNonQuery()
'I used " & TextBox3.Text & " because the textbox3 contains the path of the another database.
conn2 = New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source= '" & TextBox3.Text & "' ;Jet OLEDB:Database Password=cscfo13poppsi; ")
SQLStr2 = "INSERT INTO pop SELECT * FROM pop IN '" & TextBox3.Text & "'"
conn2.Open()
cmd2 = New OleDbCommand(SQLStr2, conn2)
cmd2.ExecuteNonQuery()
Please help me to this. Thank you.

E.g.
Using sourceConnection As New OleDbConnection("source connection string here"),
destinationConnection As New OleDbConnection("source connection string here"),
insertCommand As New OleDbCommand("INSERT statement here", destinationConnection),
adapter As New OleDbDataAdapter("SELECT statement here", sourceConnection) With {.InsertCommand = insertCommand,
.AcceptChangesDuringFill = False}
Dim table As New DataTable
adapter.Fill(table)
adapter.Update(table)
End Using
That will populate the DataTable from one database and insert the rows into the other. You'll need to configure the insertCommand with appropriate parameters. Take special note of the AcceptChangesDuringFill property, which ensures that all DataRows have a RowState of Added and are therefore ready to be inserted. Without that, all RowState properties will be Unchanged and nothing will get saved.

Related

Checking access database vb.net

I am trying to compare the values in my dictionary which contains values/quantities to a standard database containing similar values/quantities. I want to check if the value matches the database, then check if the quantity is less than the database.
I keep getting an error when I run the code on the "Using myreader" line, with the following: System.Data.OleDb.OleDbException: 'IErrorInfo.GetDescription failed with E_FAIL(0x80004005).' This is my first time using OleDBDatareader so perhaps I am doing something incorrectly. Is this not allowed, I assumed comparing a list a values in a dictionary should be possible.
Dim myconnection As OleDbConnection
Dim constring As String = "Provider=Microsoft.ACE.OLEDB.12.0; Data Source=C:\UsersTables.accdb; Persist Security Info=False"
myconnection = New OleDbConnection(constring)
myconnection.Open()
Dim keepSell As String
For Each KeyPair In colSums
Dim sqlQry As String
sqlQry = "SELECT Part,Quantity FROM PartsList WHERE Item = '" & keyPair.Key & "'AND Size= '" & keyPair.Value & "'"
Dim cmd As New OleDbCommand(sqlQry, myconnection)
Using myreader As OleDbDataReader = cmd.ExecuteReader()
If myreader.Read() Then
keepSell = "Keep"
Else
keepSell= "Sell"
End If
'myreader.Close()
End Using
DataGridView1.Rows.Add(KeyPair.Key, KeyPair.Value, keepSell)
Next

Populating an Auto-Incremented ID created through VB.net from a Parent table to multiple child tables in SQLite

New to VB.net and have been trying to get this to work for a while. As the code stands right now, I'm only able to update each table separately which makes sense but I need help getting an ID from a newly created record to the child tables in my DB. My tables are already set up with PKs and FKs and my connection string has ...foreign keys=true; in it.
Here is what I have so far:
...Dim cmd As New SQLiteCommand
cmd.Connection = myconnection
cmd.CommandText = "Insert into dbo_DataLog (ProductionDate,ProductionOrder,StyleID) values (#ProductionDate,#ProductionOrder,#StyleID)"
cmd.Parameters.AddWithValue("#ProductionDate", dtpDate.Text)
cmd.Parameters.AddWithValue("#ProductionOrder", txtProdOrder.Text)
cmd.Parameters.AddWithValue("#StyleID", StyleID)
cmd.ExecuteNonQuery()
cmd.Parameters.Clear()
Dim cmd2 As New SQLiteCommand
cmd2.Connection = myconnection
cmd2.CommandText = "Insert into dbo_WeightAndWidth (LabTech_ID,PunchWeight,OverallWidth,UsableWidth,GSM) values (#LabTech_ID,#PunchWeight,#OverallWidth,#UsableWidth,#GSM)"
cmd2.Parameters.AddWithValue("#LabTech_ID", "5")
cmd2.Parameters.AddWithValue("#PunchWeight", txtPW.Text)
cmd2.Parameters.AddWithValue("#OverallWidth", txtOW.Text)
cmd2.Parameters.AddWithValue("#UsableWidth", txtUW.Text)
cmd2.Parameters.AddWithValue("#GSM", txtGSM.Text)
cmd2.ExecuteNonQuery()
cmd2.Parameters.Clear()
myconnection.Close()...
I have done a lot of searching and can't seem to get anything to work; I know it's a pretty crappy query as is since it's just a repeat of the original.
Please assist if you're able to do so!
Edit:
Changed up my code to consolidate it and used Dim dataID As String = "Select seq from sqlite_sequence where name='dbo_DataLog'"and executed that to get utilize the temp table the SQLite uses.
Dim cmd As New SQLiteCommand
cmd.Connection = myconnection
'look up dataID that was just executed
Dim dataID As String = "Select seq from sqlite_sequence where name='dbo_DataLog'"
Dim mycmd As New SQLiteCommand(dataID, myconnection)
Dim value As Object = mycmd.ExecuteScalar()
cmd.CommandText = "Insert into dbo_DataLog (ProductionDate,ProductionOrder,StyleID) values (#ProductionDate,#ProductionOrder,#StyleID);Insert into dbo_WeightAndWidth (Data_ID,LabTech_ID,PunchWeight,OverallWidth,UsableWidth,GSM) values (#Data_ID,#LabTech_ID,#PunchWeight,#OverallWidth,#UsableWidth,#GSM) "
cmd.Parameters.AddWithValue("#ProductionDate", dtpDate.Text)
cmd.Parameters.AddWithValue("#ProductionOrder", txtProdOrder.Text)
cmd.Parameters.AddWithValue("#StyleID", StyleID)
cmd.Parameters.AddWithValue("#Data_ID", value + 1)
cmd.Parameters.AddWithValue("#LabTech_ID", "5")
cmd.Parameters.AddWithValue("#PunchWeight", txtPW.Text)
cmd.Parameters.AddWithValue("#OverallWidth", txtOW.Text)
cmd.Parameters.AddWithValue("#UsableWidth", txtUW.Text)
cmd.Parameters.AddWithValue("#GSM", txtGSM.Text)
cmd.ExecuteNonQuery()
cmd.Parameters.Clear()
myconnection.Close()

Inserting data in database using DataGridView

I am using VS 2010 and service based database and Vb.net
I want to insert data into database using DataGridView. Although, all the rows present in DataGridView are inserted in database but additional row is also inserted at the start containing ID as "0" and leaving other columns blank which I don,t want at all.
I have attached the Code and Database table for your review.
please help me to get out of this problem,
Dim Sql_ConnectionString = " DataSource=.\SQLEXPRESS;AttachDbFilename=D:\databaseapplication\DataGridView\WindowsApplication1\WindowsApplication1\Database1.mdf;IntegratedSecurity=True;User Instance=True"[Database Table Pic][1]
Try
Dim con As New SqlConnection
Dim cmd As New SqlCommand
Dim dataAdapter As New Data.SqlClient.SqlDataAdapter
con.ConnectionString = Sql_ConnectionString
cmd.Connection = con
con.Open()
For Each row As DataGridViewRow In DataGridView2.Rows
cmd.CommandText = "insert into Table4 (ID,Name,Marks) values ('" + row.Cells("cus_ID").Value + "','" + row.Cells("cus_Name").Value + "','" + row.Cells("cus_Marks").Value + "')"
cmd.ExecuteNonQuery()
Next
con.Close()

.NET OleDb parameterized query not working as expected

I'm trying to pass this Update command to a database, it completes ok with no errors but it doesnt update the database and I can't understand why?
Dim Cmd As OleDbCommand
Dim SQL As String
Dim objCmd As New OleDbCommand
Dim Con = New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & My.Settings.MasterPath)
Dim Item = "08/08/2015"
SQL = ("UPDATE [Hol Dates] SET [" & EmployeeList.Text & "]= #Htype WHERE [HDate]=#Hdate")
Cmd = New OleDbCommand(SQL, Con)
objCmd = New OleDbCommand(SQL, Con)
objCmd.Parameters.AddWithValue("#Hdate", item)
objCmd.Parameters.AddWithValue("#Htype", "None")
Con.Open()
Dim ans = MsgBox("Do you want to unbook this holiday?", MsgBoxStyle.YesNo)
If ans = MsgBoxResult.Yes Then
objCmd.ExecuteNonQuery()
Else
Exit Sub
End If
Con.Close()
Con.Dispose()
You need to reverse the order in which you add the parameters to the OleDbCommand object. OleDb allows us to assign names to parameters but it ignores the names and only pays attention to the order in which the parameters appear in the CommandText.
Therefore, since your SQL statement refers to Htype and then Hdate you need to add the parameters in that same order.

Adding SQL Parameter fails

This is a new concept for me and I can't quite see what's causing the error
I'm attempting to populate a datagridview control from a single field in an Access database (from a combo and Text box source).
Using literals works, but not with the parameter.
Dim conn As New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & Backend & ";Persist Security Info=False;")
Dim command As New OleDbCommand("Select Year from tblTest ", conn)
Dim criteria As New List(Of String)
If Not cboYear.Text = String.Empty Then
criteria.Add("Year = #Year")
command.Parameters.AddWithValue("#Year", cboYear.Text)
End If
If criteria.Count > 0 Then
command.CommandText &= " WHERE " & String.Join(" AND ", criteria)
End If
Dim UserQuery As New OleDbDataAdapter(command.CommandText, conn)
Dim UserRet As New DataTable
UserQuery.Fill(UserRet)
With frmDGV.DataGridView2
.DataSource = UserRet
End With
frmDGV.DataGridView2.Visible = True
frmDGV.Show()
Trying to Fill the datatable shows exception 'No value given for one or more required parameters.'
The value of command.CommandText at that point is "Select Year from tblTest WHERE Year = #Year"
Your instance of OleDbDataAdapter was created using two parameters query text and connection.
Dim UserQuery As New OleDbDataAdapter(command.CommandText, conn)
In this case DataAdapter doesn't know about parameters at all.
Instead use constructor with paremeter of type OleDbCommand.
Dim UserQuery As New OleDbDataAdapter(command)
In your code instance of OleDbCommand already associated with connection