我正在尝试使用以下代码从sql表中的excel文件中插入数据
foreach (var sheetName in GetExcelSheetNames(connectionString))
{
using (OleDbConnection con1 = new OleDbConnection(connectionString))
{
var dt = new DataTable();
string query = string.Format("SELECT * FROM [{0}]", sheetName);
con1.Open();
OleDbDataAdapter adapter = new OleDbDataAdapter(query, con1);
adapter.Fill(dt);
using (SqlConnection con = new SqlConnection(consString))
{
con.Open();
for (int i = 2; i < dt.Rows.Count; i++)
{
for (int j = 1; j < dt.Columns.Count; j += 3)
{
var s = dt.Rows[i][0].ToString();
s = s.Replace(",", string.Empty);
s = s.Substring(s.IndexOf(' ') + 1);
var dt1 = DateTime.Parse(s, CultureInfo.GetCultureInfo("fr-FR"));
var s1 = dt.Rows[i][j].ToString();
s1 = s1.Replace(" ", string.Empty);
var s2 = dt.Rows[i][j + 1].ToString();
s2 = s2.Replace(" ", string.Empty);
SqlCommand command = new SqlCommand("INSERT INTO [Obj CA] (CA,[VAL MRG],[Rayon],[Date],[Code Site]) VALUES(@ca,@val,'" + dt.Rows[0][j].ToString() + "', @date ,'" + sheetName + "')", con);
command.Parameters.Add("@date", SqlDbType.Date).Value = dt1;
command.Parameters.AddWithValue("@ca", s1);
command.Parameters.AddWithValue("@val", s2);
command.ExecuteNonQuery();
}
}
con.Close();
}
}
错误
System.Data.SqlClient.SqlException(0x80131904):语法不正确 关键字&#39; 01 $&#39;。在 System.Data.SqlClient.SqlConnection.OnError(SqlException异常, Boolean breakConnection)at System.Data.SqlClient.SqlInternalConnection.OnError(SQLEXCEPTION exception,Boolean breakConnection)at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning()at System.Data.SqlClient.TdsParser.Run(RunBehavior runBehavior, SqlCommand cmdHandler,SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler,TdsParserStateObject stateObj)at System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior,String resetOptionsString)at System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(的CommandBehavior cmdBehavior,RunBehavior runBehavior,Boolean returnStream,Boolean async)at System.Data.SqlClient.SqlCommand.RunExecuteReader(的CommandBehavior cmdBehavior,RunBehavior runBehavior,Boolean returnStream,String 方法,DbAsyncResult结果)at System.Data.SqlClient.SqlCommand.InternalExecuteNonQuery(DbAsyncResult result,String methodName,Boolean sendToPipe)at System.Data.SqlClient.SqlCommand.ExecuteNonQuery()at _Default.Button1_Click(Object sender,EventArgs e)在c:\ Users \ Ajaz \ Documents \ Visual Studio中 2010 \ WebSites \ WebSite26 \ Default.aspx.cs:第29行
答案 0 :(得分:0)
当您尝试将工作表名称插入[Obj CA]时,会触发您的错误。可能它有价值&#39; sheet01 $&#39;并且SQL Server无法解析$ char。
尝试重命名工作表或删除$ char,然后再将其插入表格。