我正在将Excel文件导入SQLServer数据库。该代码工作正常,但是我当前正在做的方式是删除(清除表)表数据。
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 DataRreaderdr,但是稍后将在代码中声明它。请指导我如何构造代码。
示例将不胜感激。
鉴于您的excel文件与表具有相同的结构,并且您想要更新而不是仅插入表, 最简单的方法 是使用“合并”和“表值参数”
SqlCommand cmd = 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 cmd.Parameters.AddWithValue("@source", dr); param.SqlDbType = SqlDbType.Structured; param.TypeName = "dbo.tStudent";
您的其他选择包括循环,使用登台表,将数据作为xml数据或字符串数据传递或使用ETL工具(如SSIS)。