// Collection of code snippets by Arne Vajhøj // (likely posted to comp.os.vms/INFO-VAX, INFO-TPU, MACRO32, eksperten.dk, newz.dk, LinkedIn or other place sometime between 1990 and now) using System; using System.Collections.Generic; using System.Data; using System.Data.Common; namespace E { public class DbDump { public static void DumpTbl(IDbConnection con, string db, string tbl) { IDbCommand cmd = con.CreateCommand(); cmd.CommandText = "USE " + db; cmd.ExecuteNonQuery(); cmd.CommandText = "SELECT * FROM " + tbl; List alltbl = new List(); IDataReader rdr = cmd.ExecuteReader(); while(rdr.Read()) { Console.Write("INSERT INTO " + tbl + " VALUES("); for(int i = 0; i < rdr.FieldCount; i++) { if(i > 0) Console.Write(","); object o = rdr[i]; if(o is DBNull) { Console.Write("NULL"); } else if(o is int || o is long || o is float || o is double || o is decimal) { Console.Write(o); } else if(o is string) { Console.Write("'" + o.ToString().Replace("'", "''") + "'"); } else { throw new ApplicationException("Unsupported data type"); } } Console.WriteLine(");"); } rdr.Close(); } public static void DumpDb(IDbConnection con, string db, string dbname) { Console.WriteLine("USE " + db + ";"); IDbCommand cmd = con.CreateCommand(); cmd.CommandText = "SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_" + dbname + "='" + db + "' AND TABLE_TYPE='BASE TABLE'"; List alltbl = new List(); IDataReader rdr = cmd.ExecuteReader(); while(rdr.Read()) { alltbl.Add((string)rdr[0]); } rdr.Close(); foreach(string tbl in alltbl) { DumpTbl(con, db, tbl); } } public static void Dump(IDbConnection con, string dbname) { IDbCommand cmd = con.CreateCommand(); cmd.CommandText = "SELECT DISTINCT TABLE_" + dbname + " FROM INFORMATION_SCHEMA.TABLES"; List alldb = new List(); IDataReader rdr = cmd.ExecuteReader(); while(rdr.Read()) { string db = (string)rdr[0]; if(!db.StartsWith("sys") && !db.Equals("mysql")) { alldb.Add(db); } } rdr.Close(); foreach(string db in alldb) { DumpDb(con, db, dbname); } } public static void Dump(string provider, string constr, string dbname) { DbProviderFactory dbf = DbProviderFactories.GetFactory(provider); using(IDbConnection con = dbf.CreateConnection()) { con.ConnectionString = constr; con.Open(); Dump(con, dbname); } } } public class Program { public static void Main(string[] args) { DbDump.Dump("System.Data.SqlClient", @"Server=ARNEPC3\SQLEXPRESS;Integrated Security=SSPI;Database=Test", "CATALOG"); DbDump.Dump("MySql.Data.MySqlClient", "Data Source=localhost;Database=Test;User Id=root;Password=", "SCHEMA"); } } }