0

我正在使用VS2005 C#和SQL Server 2005.我目前正在爲.CSV excel文件數據導入到我的SQL Server數據庫中。C#VS2005查詢表達式中的語法錯誤(缺少運算符)

我有一些錯誤,我認爲這與我的sql語句有關。下面是我的代碼: 「在查詢表達式語法錯誤(缺少運算符) '[說明] FROM20111109164041.csv'」

protected void Button1_Click(object sender, EventArgs e) 
    { 
     if (FileUpload1.HasFile) 
     { 
      // Get the name of the Excel spreadsheet to upload. 
      string strFileName = Server.HtmlEncode(FileUpload1.FileName); 

      // Get the extension of the Excel spreadsheet. 
      string strExtension = Path.GetExtension(strFileName); 

      // Validate the file extension. 
      if (strExtension != ".xls" && strExtension != ".xlsx" && strExtension != ".csv" && strExtension != ".csv") 
      { 
       Response.Write("<script>alert('Failed to import DEM Conflicting Role Datasheet. Cause: Invalid Excel file.');</script>"); 
       return; 
      } 

      // Generate the file name to save. 
      string dir = @"C:\Documents and Settings\rhlim\My Documents\Visual Studio 2005\WebSites\SoD\UploadFiles\"; 
      string mycsv = DateTime.Now.ToString("yyyyMMddHHmmss") + strExtension; 
      // Save the Excel spreadsheet on server. 
      FileUpload1.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 [TABLES] FROM" + mycsv, ExcelConnection); 

      OleDbDataAdapter ExcelAdapter = new OleDbDataAdapter(ExcelCommand); 

      ExcelConnection.Open(); 

      using (DbDataReader dr = ExcelCommand.ExecuteReader()) 
      { 
       // SQL Server Connection String 
       string sqlConnectionString = "Data Source=<IP>;Initial Catalog=<DB>;User ID=<UID>;Password=<PW>"; 

       // Bulk Copy to SQL Server 
       using (SqlBulkCopy bulkCopy = 
          new SqlBulkCopy(sqlConnectionString)) 
       { 
        bulkCopy.DestinationTableName = "DEMUserRoles"; 
        bulkCopy.WriteToServer(dr); 
        Response.Write("<script>alert('DEM User Data imported');</script>"); 

       } 
      } 
      } 
     } 
     else Response.Write("<script>alert('Failed to import DEM User Roles Data. Cause: No file found.');</script>"); 
    } 

我收到錯誤

while(DbDataReader dr = ExcelCommand.ExecuteReader())執行時。說明是我數據庫中的最後一列。

任何人都知道我的代碼有什麼問題嗎?謝謝

enter image description here

回答

4

您需要和CSV文件之間的空間! :)

OleDbCommand ExcelCommand = new OleDbCommand("SELECT [TABLES] FROM " + mycsv, ExcelConnection); 

這就是爲什麼我總是用String.Format方法,你會看到更好的,最後一個字符串的樣式:

OleDbCommand ExcelCommand = new OleDbCommand(string.Format("SELECT [TABLES] FROM {0}",mycsv), ExcelConnection); 
2

好像你需要廣場之間的空白您CSV-文件: '[說明] FROM 20111109164041.csv'

+0

我愛你哥們!謝謝 – gymcode

0

如果要添加,你應該把它放在單引號之間的字符串

OleDbDataAdapter da = new OleDbDataAdapter("select * , '" + tempUid + "' as [UID] from [" + sheet1 + "]", conn); 
相關問題