using System; using System.Data.SqlClient; using System.Data; namespace SqlBulkCopyTest { class Program { static void Main() { Console.Write("Enter Data Source: "); string server = Console.ReadLine(); Console.Write("Enter Initial Catalog: "); string dbname = Console.ReadLine(); Console.Write("Enter User ID: "); string username = Console.ReadLine(); Console.Write("Enter Password: "); string password = Console.ReadLine(); string connectionString = GetConnectionString(server, dbname, username, password); // Open a sourceConnection to the database. using (SqlConnection sourceConnection = new SqlConnection(connectionString)) { sourceConnection.Open(); // Create a table with some rows. DataTable newData = MakeTable(); // Open the destination connection. using (SqlConnection destinationConnection = new SqlConnection(connectionString)) { destinationConnection.Open(); // Set up the bulk copy object. using (SqlBulkCopy bulkCopy = new SqlBulkCopy(destinationConnection)) { Console.Write("Enter Table Name: "); string tableName = Console.ReadLine(); bulkCopy.DestinationTableName = tableName; bulkCopy.BulkCopyTimeout = 0; try { // Write from the source to the destination. bulkCopy.WriteToServer(newData); } catch (Exception ex) { Console.WriteLine(ex.Message); } } } } } private static DataTable MakeTable() // Create a new DataTable named Data. { DataTable mhdData = new DataTable("Data"); // Add three column objects to the table. DataColumn timestep = new DataColumn(); timestep.DataType = System.Type.GetType("System.Int32"); timestep.ColumnName = "timestep"; mhdData.Columns.Add(timestep); DataColumn zindex = new DataColumn(); zindex.DataType = System.Type.GetType("System.Int64"); zindex.ColumnName = "zindex"; mhdData.Columns.Add(zindex); DataColumn data = new DataColumn(); data.DataType = System.Type.GetType("System.Byte[]"); data.ColumnName = "data"; mhdData.Columns.Add(data); // Add some new rows to the collection. DataRow row; byte[] bytes = new byte[3]; for (int k = 0; k <= 7; k++) for (int j = 0; j <= 7; j++) for (int i = 0; i <= 7; i++) { bytes[0] = (byte)i; bytes[1] = (byte)j; bytes[2] = (byte)k; row = mhdData.NewRow(); row["timestep"] = 0; row["zindex"] = i + 8*j + 64*k; row["data"] = bytes; mhdData.Rows.Add(row); } mhdData.AcceptChanges(); // Return the new DataTable. return mhdData; } private static string GetConnectionString(string server, string dbname, string username, string password) // To avoid storing the sourceConnection string in your code, // you can retrieve it from a configuration file. { return String.Format("Server={0}; " + " Database={1};" + "User ID={2}; Password={3}", server, dbname, username, password); // The following connection string does not seem to work with mono. // However, it is a valid connection string for MS SQL Server. //return String.Format("Data Source={0}; " + //"Initial Catalog={1}; User ID={2}; Password={3}; Connection Timeout=0;", // server, dbname, username, password); } } }