SQL Attach 'User.Identity.Name'随着excel数据导入到SQL Serve
本文关键字:SQL 数据 导入 excel Serve Identity Attach User Name 随着 | 更新日期: 2023-09-27 18:16:13
我使用VS2005 c#和SQL Server 2005。
我有一个Excel文件导入,它将电子表格中的数据导入数据库。
然而,为了改进它,我想对每次导入实现某种"日志记录"。
对于用户导入的每一行数据,将有一列用于存储登录用户的名称,即User.Identity.Name
。
下面是我的excel导入代码片段:
// Create Connection to Excel Workbook
string connStr = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + strUploadFileName + ";Extended Properties=Excel 8.0;";
using (OleDbConnection connection = new OleDbConnection(connStr))
{
OleDbCommand command = new OleDbCommand("Select [User ID], [Username], [Age], [Address], [Date of Reg], [Membership Type], [Membership Expiry] FROM [sheet1$]", connection);
//would like to insert 'User.Identity.Name' into column 'userlog'
connection.Open();
Console.WriteLine("Connection Opened");
// Create DbDataReader to Data Worksheet
using (DbDataReader dr = command.ExecuteReader())
{
// SQL Server Connection String
string sqlConnectionString = "Data Source=<DS>";
// Bulk Copy to SQL Server
using (SqlBulkCopy bulkCopy = new SqlBulkCopy(sqlConnectionString))
{
bulkCopy.DestinationTableName = "UserData";
bulkCopy.WriteToServer(dr);
}
}
}
我不知道如何做到这一点,因为SELECT
语句只从我导入的数据的sheet1$
中获取变量,所以我不知道如何从另一个源将另一个变量包含到sql查询中。我需要有经验的人的建议。
提前感谢大家的帮助。
编辑:我有另一个.csv
类型的导入方法。由于SELECT
语句与我用于.xls
的语句不一样,我应该如何更改它?下面是代码片段:
string dir = @"C:'...'UploadFiles";
string mycsv = DateTime.Now.ToString("yyyyMMddHHmmss") + strExtension;
// Save the Excel spreadsheet on server.
UserImport.SaveAs(dir + mycsv);
// Create Connection to Excel Workbook
string connStr = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + dir +
";Extended Properties=Text;";
using (OleDbConnection ExcelConnection = new OleDbConnection(connStr))
{
OleDbCommand ExcelCommand = new OleDbCommand(
"SELECT [User ID], [Username], [Age], [Address],
[Date of Reg], [Membership Type], [Membership Expiry]
FROM " + mycsv, ExcelConnection);
OleDbDataAdapter ExcelAdapter = new OleDbDataAdapter(ExcelCommand);
ExcelConnection.Open();
using (DbDataReader dr = ExcelCommand.ExecuteReader())
{
// SQL Server Connection String
string sqlConnectionString = "Data Source=<DS>";
// Bulk Copy to SQL Server
using (SqlBulkCopy bulkCopy = new SqlBulkCopy(sqlConnectionString))
{
bulkCopy.DestinationTableName = "UserData";
bulkCopy.WriteToServer(dr);
//Response.Write("<script>alert('User Data imported');</script>");
}
}
}
谢谢
你可以尝试扩展你的select子句。
string selectStmt = string.Format("Select [User ID], [Username], [Age], [Address],
[Date of Reg], [Membership Type], [Membership Expiry],
'{0}' as [userlog] FROM [sheet1$]", User.Identity.Name);
OleDbCommand command = new OleDbCommand(selectStmt, connection);
根据您的编辑的问题更新
string selectStmt = string.Format("SELECT [User ID], [Username], [Age], [Address],
[Date of Reg], [Membership Type], [Membership Expiry],'{0}' as [userlog]
FROM {1}", User.Identity.Name, mycsv);
你可以创建一个DataTable,它将包含你的Excel数据和你的身份名,然后批量复制这个DataTable到你的SQL Server。