2014-10-02 57 views
0

插入文件路徑字符串轉換成SQL數據庫在SQL:通過C#代碼

INSERT INTO [dbo].[tblFiles] 
      ([FullFilePath] 
      ,[LastModified]) 
    VALUES 
      ('P:\test\test.csv', 
      null) 

這將存儲在數據庫中的完整路徑:) 不過,我需要做到這一點的代碼。

SqlConnection connection = new SqlConnection(DatabaseHelper.ConnectionString); 
    connection.Open(); 

    SqlCommand command = new SqlCommand("stpInsertFile", connection); 
    command.CommandType = System.Data.CommandType.StoredProcedure; 
    command.Parameters.Add(new SqlParameter("@filepath", System.Data.SqlDbType.VarChar)); 
    command.Parameters["@filepath"].Value = article.FullFilePath; 

    command.Parameters.Add(new SqlParameter("@LastModified", System.Data.SqlDbType.DateTime)); 
    command.Parameters["@LastModified"].Value = article.LastModified; 


    int newArticleID = Convert.ToInt32((decimal)command.ExecuteNonQuery()); 

    command.Dispose(); 
    connection.Close(); 
    connection.Dispose(); 

    return newArticleID; 

這樣我得到的就是'P'的完整路徑列。 所以我嘗試使用LINQ並得到了相同的結果。

public int InsertArticleUsingLINQ(tblFile article) { 
      DataClassesDataContext context = new DataClassesDataContext(); 

       tblFile newFileEntry = new tblFile(); 
       newFileEntry.FullFilePath = article.FullFilePath; 
       newFileEntry.LastModified = article.LastModified; 
       context.tblFiles.InsertOnSubmit(newFileEntry); 
       context.SubmitChanges(); 

       return newFileEntry.ID; 

     } 

在將字符串傳遞給數據庫插入函數之前,我沒有對該字符串做任何處理。我讀到,你需要避開反斜槓,但它似乎是逃避報價。還請閱讀你在sql之前需要@符號,但是如何將它添加到參數中?

+0

'stpInsertFile'是做什麼的? – 2014-10-02 11:11:10

+0

article.FullFilePath持有什麼值?在插入它之前可能會出錯。 – 2014-10-02 11:17:16

+0

當您設置'command.Parameters [「@ filepath」]時,您可能需要添加引號。值' – 2014-10-02 11:19:24

回答

1

警告:既然你沒有共享存儲過程代碼,這只是一個瘋狂的猜測。

您是否在存儲過程的定義中設置了@filePath參數的大小?

,如果你把它聲明爲:

create procedure stpInsertFile 
    @filepath  varchar, 
    @LastModified datetime 
as 
... 

那麼你參數創建爲varchar(1)因爲varchar數據類型的默認行爲,並會產生你得到的結果。
請在ms網站上查詢reference documentation以獲取char和varchar數據類型。

+0

是的,就是這樣。一個容易犯的錯誤? – JohnnyBizzle 2014-10-02 12:53:45

1

如果stpInsertFile是一個存儲過程,你會在你的代碼來設置:

... 
command.CommandType = CommandType.StoredProcedure; 

否則你必須設置查詢字符串在你的命令:

SqlCommand command = new SqlCommand("INSERT INTO [dbo].[tblFiles] ([FullFilePath] [LastModified]) VALUES (@filepath,@LastModified)", connection); 
... 
+0

我在第4行做過 – JohnnyBizzle 2014-10-02 12:03:05

0

上述選項中,即使手動添加引號,ADO代碼也不會複製完整路徑。我所得到的只是數據庫中的一個字符。

進一步檢查時,參數類型爲Varchar(1)!!!我改變了它的Varchar(255)它的工作。

請注意,LINQ to SQL函數確實插入了完整路徑,因爲它沒有使用存儲過程。

道歉的錯誤。