Solved

Difficults copy data from DataTable to another. Need someone to check code!

Posted on 2014-01-03
6
476 Views
Last Modified: 2014-01-06
Hello,
I'm trying to import data from access table to sql table, through Dataset DataTables. Below code just dont want work for me. even any error does not appear.
T2 is table from access database, T2main is table from sql database. They have indentical column names, and type.

Imports System.Data
Imports System.Data.SqlClient
Partial Class Default2
    Inherits System.Web.UI.Page

    Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
        Dim AccessT2 As New DataTable("T2")
        Dim SqlT2 As New DataTable("T2main")
        For Each dr As DataRow In AccessT2.Rows
            Try
               AccessT2.Copy()
                SqlT2.ImportRow(dr)
            Catch ex As Exception
                MsgBox(ex.Message)
            End Try
        Next
    End Sub
End Class

Open in new window


protected void Button1_Click(object sender, System.EventArgs e)
{
	DataTable AccessT2 = new DataTable("T2");
	DataTable SqlT2 = new DataTable("T2main");
	foreach (DataRow dr in AccessT2.Rows) {
		try {
			AccessT2.Copy();
			SqlT2.ImportRow(dr);
		} catch (Exception ex) {
			Interaction.MsgBox(ex.Message);
		}
	}
}

Open in new window


Thanks in advance for help.
0
Comment
Question by:dejandejanovic
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 3
  • 3
6 Comments
 
LVL 52

Expert Comment

by:Carl Tawn
ID: 39753503
What is it you are trying to achieve? At the moment all you have done is create two empty DataTables. You're not getting any rows in your loop because both of those DataTables are empty.
0
 

Author Comment

by:dejandejanovic
ID: 39753506
To copy rows/records from one table to another...
0
 

Author Comment

by:dejandejanovic
ID: 39753513
Your comment make sense now to me. For any suggestion, tips I would be pleased if you could provide...
0
Instantly Create Instructional Tutorials

Contextual Guidance at the moment of need helps your employees adopt to new software or processes instantly. Boost knowledge retention and employee engagement step-by-step with one easy solution.

 
LVL 52

Accepted Solution

by:
Carl Tawn earned 500 total points
ID: 39753565
Assuming you need to actually load data from an Access database and copy it to a SQL Server database, you are going to need a few things.

1) A OleDbConnection object for your access database, along with an OleDbDataAdapter to retrieve the data.

2) A SqlConnection object and SqlDataAdapter objects to load the data and push it to you SQL server.

This sample should get you started:
            // create connection for Access database
            OdbcConnection odbcConn = new OdbcConnection("Driver=Microsoft Access Driver (*.mdb);Dbq=C:\\Test.mdb;");
            OdbcDataAdapter odbcAdap = new OdbcDataAdapter("SELECT PersonID, FirstName, LastName FROM People", odbcConn);

            // create connection for SQL Server database
            SqlConnection sqlConn = new SqlConnection("Server=.\\SQLEXPRESS;Initial Catalog=CarlDemo;Integrated Security=SSPI;");
            SqlDataAdapter sqlAdap = new SqlDataAdapter("SELECT PersonID, FirstName, LastName FROM People", sqlConn);

            // configure INSERT statement for SQL Server database
            SqlCommandBuilder builder = new SqlCommandBuilder(sqlAdap);
            sqlAdap.InsertCommand = builder.GetInsertCommand();

            // retrieve data from Access
            DataTable accessData = new DataTable();
            odbcAdap.Fill(accessData);

            // mark each row as new so it will get inserted
            foreach (DataRow row in accessData.Rows)
                row.SetAdded();

            // push data to SQL Server
            sqlAdap.Update(accessData);

Open in new window


I'd suggest you read up on data access to more fully understand the components you are using.

You can find a basic introduction to data access on my blog here: http://myvirtualplayground.co.uk/blog/Fundamentals_Reading_From_a_Database_Part_1
0
 

Author Closing Comment

by:dejandejanovic
ID: 39758666
Thanks Carl. Your guide was 100% helpful for me.
If might someone will needed int the future, below is a little bit changed code, but still same methods.

Dim AccessData As New DataTable
        Try
            Dim connection As New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=TEST.mdb")
            connection.Open()
            Dim adapter As New OleDbDataAdapter
            Dim userdataset As New DataSet
            Dim command As New OleDbCommand
            command.CommandText = "SELECT * FROM TEST"
            command.Connection = connection
            adapter.SelectCommand = command
            adapter.Fill(AccessData)
            connection.Close()
            For Each row As DataRow In AccessData.Rows
                row.SetAdded()
            Next
            MsgBox("Access conn successful")
        Catch ex As Exception
            MsgBox("access error: " + ex.Message)
        End Try

        Try
            'create connection for SQL Server database
            Dim Sqlconn As New SqlConnection("Data Source=SQLDB;Initial Catalog=TEST;Persist Security Info=True;User ID=sa;Password=********")
            Sqlconn.Open()
                        Dim SqlAdapter As New SqlDataAdapter("SELECT * FROM TEST", Sqlconn)
                       Dim builder As New SqlCommandBuilder(SqlAdapter)
            builder.GetInsertCommand()
            SqlAdapter.Update(AccessData)
            Sqlconn.Close()
            MsgBox("sql conn successful")
        Catch ex As Exception
            MsgBox("sql error: " + ex.Message)
        End Try

Open in new window

0
 
LVL 52

Expert Comment

by:Carl Tawn
ID: 39758686
Glad you found it helpful.

Just one quick note though - you don't need to manually open and close the database connection when using the DataAdapters. The Fill() and Update() methods will take care of that for you.
0

Featured Post

Free Tool: Path Explorer

An intuitive utility to help find the CSS path to UI elements on a webpage. These paths are used frequently in a variety of front-end development and QA automation tasks.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
How to save a java script "this" object in an asp.net hidden variable. 4 23
Adjust the codes 3 60
Windows Universal App 22 52
Select coumns form Data table? 3 23
International Data Corporation (IDC) prognosticates that before the current the year gets over disbursing on IT framework products to be sent in cloud environs will be $37.1B.
This article aims to explain the working of CircularLogArchiver. This tool was designed to solve the buildup of log file in cases where systems do not support circular logging or where circular logging is not enabled
The Email Laundry PDF encryption service allows companies to send confidential encrypted  emails to anybody. The PDF document can also contain attachments that are embedded in the encrypted PDF. The password is randomly generated by The Email Laundr…
In a recent question (https://www.experts-exchange.com/questions/29004105/Run-AutoHotkey-script-directly-from-Notepad.html) here at Experts Exchange, a member asked how to run an AutoHotkey script (.AHK) directly from Notepad++ (aka NPP). This video…

738 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question