jeudi 5 mars 2015

Copy Data from one Sqlite table to another Sqlite table

I need to copy data from one Sqlite table to another. I wrote method, which return DataTable:



public static DataTable GetDataFromSecondTable(string filePath)
{
DataTable DbTable = new DataTable("Messages");
using (var connection = new SQLiteConnection(filePath))
{
string SelectQuery = "SELECT * FROM Messages";
using (SQLiteCommand cmd = new SQLiteCommand(SelectQuery, connection))
{
connection.Open();

using (SQLiteDataAdapter adapter = new SQLiteDataAdapter(cmd))
{
adapter.Fill(DbTable);
}
}
}
return DbTable;
}


Then I need to insert this DataTable to my "main" table, which has same structure:



public static void MergeData(string mainDbPath, string secondDbPath)
{
DataTable secondTable = GetDataFromSecondTable(secondDbPath);

using(SQLiteConnection connect = new SQLiteConnection(mainDbPath))
{
connect.Open();
using (var cmd = new SQLiteCommand(connect))
{
using (var transaction = connect.BeginTransaction())
{
foreach(DataColumn column in secondTable.Columns)
{
foreach(DataRow row in secondTable.Rows)
{
//cmd.CommandText = String.Format("INSERT INTO Messages ('{0}') VALUES('{1}')", column.ColumnName, row);
cmd.ExecuteNonQuery();
}
}

transaction.Commit();
}
}
}

}


I don't understand how I should set rows and columns to SQLite query. Maybe someone have another solution for this task.


Aucun commentaire:

Enregistrer un commentaire