2011-12-27 23 views
2

在sqllite我有日期和我有一個查詢:日期時間在SQL中不同的本地化

INSERT INTO stats_project_funds(id_project, id_funds, month,stake, stake_in_units, stake_in_percent, profit, profit_in_units, picks, hitrate, won, draw, lost) 
VALUES(1, 5, strftime("%Y-%m",'27.12.2011'), 0, 0, 0, 0, 0, 0, 0, 0, 0, 0); 

正如你所看到的日期是在俄羅斯的格式。我的程序使用日期格式爲27-12-2011的歐洲本地化語言編寫。我必須改變這個查詢將適用於所有本地化?現在數據庫中的這個字段是數據時間類型。更好的解決方案將它更改爲varchar並插入字符串值?在字段中只存儲年份和月份。

我的查詢看起來是這樣的:

DateTime newMonth = DateTime.Parse(month); 
      StringBuilder query = new StringBuilder(); 
      query.AppendFormat(" INSERT INTO stats_project_funds(id_project, id_funds, month,stake, stake_in_units, " 
       + " stake_in_percent, profit, profit_in_units, picks, hitrate, won, draw, lost) " 
       + " VALUES({0}, {1}, strftime(\"%Y-%m\",'{2}'), 0, 0, 0, 0, 0, 0, 0, 0, 0, 0); ", idProject, idFunds, newMonth.Date.ToShortDateString()); 
      return query.ToString(); 

感謝

+3

爲什麼不把它存儲在正常的日期時間,只是在你想要的日期做一個格式。只是好奇爲什麼你不會使用DateTime作爲你的字段類型。 – MethodMan 2011-12-27 17:23:31

+0

現在它在正常的DateTime和格式是歐洲的,但這是問題strftime(\「%Y-%m \」,'{2}'),因爲在俄語版本中它應該是strftime(\「%Y.%m \」,'{2}') – Robert 2011-12-27 17:26:16

+0

DateTime不具有**格式 - 它只是一個數字。我只是推遲任何格式問題的應用層,並讓數據庫只處理原始值(通過輸入參數,根據當前的答案) – 2011-12-27 18:16:17

回答

3

我會用參數而不是字符串構建,它是更清潔,更安全,更容易出錯。這樣,您不必擔心日期格式,這是處理參數的首選方式。

IDbCommand db = 
    new SqlCommand("insert into table (myDateField) values (@myDateParam)"); 
db.Parameters.Add(new SqlParameter("@myDateParam", DateTime.Now)); 
+0

newMonth.Date.ToString(「yyyy-MM」,CultureInfo.CurrentCulture)工程在所有國家:) – Robert 2011-12-27 18:15:47