2014-12-02 108 views
1

我想創建一個.NET應用程序,它將信息存儲在SQLite文件中。我遇到的問題是執行SQL命令後,只有一條記錄可見,就像當前行被覆蓋一樣。Sqlite插入覆蓋記錄

創建表:

bool pathExist = Directory.Exists(appdataPath + "OnCallDB.sqlite"); 

if (!pathExist) 
{ 
    SQLiteConnection.CreateFile(appdataPath + "OnCallDB.sqlite"); 
    SQLiteConnection dbNewConnection = new SQLiteConnection("Data Source=" + appdataPath + "OnCallDB.sqlite;Version=3;"); 
    dbNewConnection.Open(); 
    string sqlTableCreation = "CREATE TABLE Calls (Id Integer PRIMARY KEY, name varchar(30), ticket varchar(20), phone varchar(20), day varchar(20), start_time varchar(20), end_time varchar(20), raw_time varchar(20), weighted_time varchar(20), date DATETIME, notes varchar(255))"; 
    SQLiteCommand command = new SQLiteCommand(sqlTableCreation, dbNewConnection); 
    command.ExecuteNonQuery(); 
    dbNewConnection.Close(); 
} 

Insert語句:

SQLiteCommand insertCommand = new SQLiteCommand("INSERT INTO Calls ([name], [ticket], [phone], [day], [start_time], [end_time], [raw_time], [weighted_time], [date], [notes])"+ 
    "VALUES(@name, @ticket, @phone, @day, @start_time, @end_time, @raw_time, @weighted_time, @date, @notes)",connection); 

insertCommand.Parameters.AddWithValue("@name", name); 
insertCommand.Parameters.AddWithValue("@ticket", ticket); 
insertCommand.Parameters.AddWithValue("@phone", phone); 
insertCommand.Parameters.AddWithValue("@day", day); 
insertCommand.Parameters.AddWithValue("@start_time", start_time); 
insertCommand.Parameters.AddWithValue("@end_time", end_time); 
insertCommand.Parameters.AddWithValue("@raw_time", raw_time); 
insertCommand.Parameters.AddWithValue("@weighted_time", weighted_time); 
insertCommand.Parameters.AddWithValue("@date", date); 
insertCommand.Parameters.AddWithValue("@notes", notes); 

try 
{ 
    connection.Open(); 
    insertCommand.ExecuteNonQuery(); 
    connection.Close(); 
} 
catch(Exception ex) 
{ 
    throw new Exception(ex.Message); 
} 

我已經手動運行該命令的SQL文件,並插入一個新行。當我運行上面的SQLite命令時,它將替換該行。據我所知。我查看了文件的創建日期和時間,看起來該文件剛剛被修改並且沒有被替換。

+0

我必須承認我沒有看到命令本身的問題。我從來沒有聽說過一個插入行爲作爲更新...你檢查數據庫值,看看第二個插入是否有效地取代第一個? – Jauch 2014-12-02 01:05:06

+0

Sqlite似乎能夠在插入時替換,例如,如果違反了密鑰,但只有在使用on conflict子句時,我認爲。試圖用同樣的鑰匙包括第二個重新加入的樂曲時,你是否會遇到異常情況?什麼是Id字段?我認爲你錯過了插入的ID和默認值將違反密鑰 – Jauch 2014-12-02 01:14:15

+2

你不是多次運行表創建方法......對吧?我擔心的是,根據代碼和設計的結構,您有可能覆蓋表格。代碼中沒有指向REPLACE衝突解決算法或ON CONFLICT子句。我甚至不知道會有什麼影響......考慮到我只知道DROP TABLE,嗯。 – 2014-12-02 04:56:46

回答

1

問題不在於SQL語句。問題是如何創建文件

+0

你能解釋更多的細節? – Jauch 2014-12-02 18:12:19

+0

它應該是: bool pathExist = Directory.Exists(appdataPath); bool fileExist = File.Exists(appdataPath +「OnCallDB.sqlite」); 由於「OnCallDB.sqlite」是一個文件而不是一個目錄,因此bool被傳遞爲false。愚蠢的錯誤。感謝您的幫助 – user3930238 2014-12-02 21:39:40

+1

所以,實際上你是在蹂躪文件。它發生了。不好,我們沒有看到。 – Jauch 2014-12-03 09:15:37