2013-05-14 50 views
2

我正在使用c#應用程序來加載一個postgresql表與適當的數據。下面是代碼:錯誤42601語法錯誤在或接近

NpgsqlConnection conn = new NpgsqlConnection("Server=localhost;Port=5432;UserId=postgres;Password=***** ;Database=postgres;"); 
NpgsqlCommand command = new NpgsqlCommand(); 
command.Connection = conn; 
conn.Open(); 
try { 
    command.CommandText = "insert into projets (ID, Title, Path, Description, DateCreated) values('" + pro.ID + "','" + pro.Title + "','" + pro.Path + "', '' ,'" + pro.DateCreated + "')"; 
    command.ExecuteNonQuery(); 
} catch { 
    throw; 
} 
conn.Close(); 

但是,執行代碼時,我不斷收到同樣的錯誤:

error 42601 syntax error at or near... 

我沒有找到如何逃脫的APOSTROPH。

+0

你確定你插入'projets'而不是'projects'嗎? – Brandon 2013-05-14 14:52:51

+0

錯誤在或接近* what *? – 2013-05-14 14:57:14

+1

除了@Brandon所說的之外,我還會推薦使用[SqlParameters](http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlparameter.aspx)來解決問題完全轉義字符串,並有助於同時防止SQL注入攻擊。 – DGibbs 2013-05-14 14:58:45

回答

1

嘗試使用參數化查詢

command.CommandText = "insert into projets (ID, Title, Path, Description, DateCreated) " + 
        "values(@id, @title, @path, '', @dt);"; 
command.Parameters.AddWithValue("@id", pro.ID); 
command.Parameters.AddWithValue("@title", pro.Title); 
command.Parameters.AddWithValue("@path", pro.PAth) 
command.Parameters.AddWithValue("@dt", pro.DateCreated); 
command.ExecuteNonQuery(); 

這樣,如果你的字符串值中的一個包含一個單引號,你離開工作,正確分析自己的價值觀的框架代碼來寫你的命令,你避免出現問題Sql Injection

+1

謝謝soooooooooo多:) – user2311028 2013-05-14 15:19:29

相關問題