我正在将 excel 文件导入 sql server 数据库。该代码工作正常,但我目前正在做的方式是删除(清除表格)表格数据。
string ssqltable = "tStudent";
string myexceldataquery = "select id,student,rollno,course from [sheet1$]";
try
{
string sexcelconnectionstring = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source =" + excelfilepath + "; Extended Properties=\"Excel 12.0; HDR=Yes; IMEX=2\"";
string ssqlconnectionstring = "Data Source=DELL\\SQLSERVER1;Trusted_Connection=True;DATABASE=Test;CONNECTION RESET=FALSE";
SqlConnection sqlconn = new SqlConnection(ssqlconnectionstring);
SqlCommand sqlcmd = new SqlCommand(@"MERGE tStudent AS target
USING (select ID, STUDENT , ROLLNO from @source) as source
ON (source.ID = target.ID)
WHEN MATCHED THEN
UPDATE SET Student = source.Student,
ROLLNO = source.ROLLNO
WHEN NOT MATCHED THEN
INSERT (ID, STUDENT , ROLLNO)
VALUES (source.id, source.Student, source.RollNo);", sqlconn);
******************************************
SqlParameter param = new SqlParameter();
sqlcmd.Parameters.AddWithValue("@source", dr);
param.SqlDbType = SqlDbType.Structured;
param.TypeName = "dbo.tStudent";
******************************************
sqlconn.Open();
sqlcmd.ExecuteNonQuery();
sqlconn.Close();
//series of commands to bulk copy data from the excel file into our sql table
OleDbConnection oledbconn = new OleDbConnection(sexcelconnectionstring);
OleDbCommand oledbcmd = new OleDbCommand(myexceldataquery, oledbconn);
oledbconn.Open();
OleDbDataReader dr = oledbcmd.ExecuteReader();
SqlBulkCopy bulkcopy = new SqlBulkCopy(ssqlconnectionstring);
bulkcopy.DestinationTableName = ssqltable;
bulkcopy.WriteToServer(dr);
while (dr.Read())
{
//bulkcopy.WriteToServer(dr);
}
oledbconn.Close();
Console.WriteLine(".xlsx file imported succssessfully into database.", bulkcopy.NotifyAfter);
}
见*部分。我已经在 Sqlparameters 中分配了我的 OleDb DataRreader dr,但我稍后会在代码中声明它。请指导我如何构建我的代码。
示例将不胜感激。