-2
私はSQLデータベースにExcelをインポートする必要があります。私はアップロードボタンの下にすべてのコードを書いている。クラス/メソッドを介して接続を渡す必要があります
しかし、クラス/メソッドを別々に記述し、ボタンクリック時にSQLを記述しないでください。
親切に私はプログラミングに新しいです、私を助けて
マイ合計コード:私は大量にデータを挿入するSQLコマンドに関連DbDataReader
オブジェクトを使用して多くの成功を持っていた
private void SaveFileToDatabase(string filePath)
{
if (Path.GetExtension(filePath) == ".xls")
{
excelConnString = String.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0}; Extended Properties=\"Excel 12.0\"", filePath);
}
else if (Path.GetExtension(filePath) == ".xlsx")
{
excelConnString = String.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0}; Extended Properties='Excel 12.0 Xml'", filePath);
}
// Importing a file data to Database
// Create Connection to Excel work book
OleDbConnection Oledbconn = new OleDbConnection(excelConnString);
OleDbCommand cmd = new OleDbCommand();
cmd.Connection = Oledbconn;
OleDbDataAdapter da = new OleDbDataAdapter(cmd);
Oledbconn.Open();
DataTable dtSheet = Oledbconn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
Oledbconn.Close();
// iterate each sheet
foreach (System.Data.DataRow sheet in dtSheet.Rows)
{
Oledbconn.Open();
DataTable dt = new DataTable();
string sheetName = sheet["table_name"].ToString();
cmd.CommandText = "select * from [" + sheetName + "]";
da.SelectCommand = cmd;
da.Fill(dt);
ISqlMapper sqlMapper = ApplicationContainer.Current.Resolve<ISqlMapper>("StageDB");
ISqlMapSession SqlMapSession = sqlMapper.OpenConnection();
SqlMapSession.Connection.Open();
using (SqlBulkCopy sqlBulk = new SqlBulkCopy(SqlMapSession.Connection.ConnectionString))
{
// Destination table name. Table name is sheet name minus any $
sqlBulk.DestinationTableName = sheetName.Replace("$", "");
foreach (var column in dt.Columns)
{
sqlBulk.ColumnMappings.Add(column.ToString(), column.ToString());
}
sqlBulk.WriteToServer(dt);
}
Oledbconn.Close();
sqlMapper.CloseConnection();
}
**The code which I have to make a class and just callhere:**
ISqlMapper sqlMapper = ApplicationContainer.Current.Resolve<ISqlMapper>("StageDB");
ISqlMapSession SqlMapSession = sqlMapper.OpenConnection();
SqlMapSession.Connection.Open();
using (SqlBulkCopy sqlBulk = new SqlBulkCopy(SqlMapSession.Connection.ConnectionString))
{
// Destination table name. Table name is sheet name minus any $
sqlBulk.DestinationTableName = sheetName.Replace("$", "");
foreach (var column in dt.Columns)
{
sqlBulk.ColumnMappings.Add(column.ToString(), column.ToString());
}
sqlBulk.WriteToServer(dt);
}
Oledbconn.Close();
sqlMapper.CloseConnection();
}
だから何が正確に問題がありますか?あなたはクラスを作る方法を尋ねていますか? – Trey
はいSQL Bulkcopyのためにクラス/メソッドを個別に作成する必要があります。ページロード時にsqlを使用しないように、ページでそれを呼び出す必要があります。 – King
https://msdn.microsoft.com/en-us/library/x9afc042.aspx – Trey