2012-08-09 85 views
0

我有一個查詢,它從datematch上的sql server中獲取信息。c中的SQL Server日期存儲#

我已經搜索了很多關於SQL Server的日期字符串,我只是想與日期匹配並從數據庫中獲取數據。此外,我正在使用SQL Server 2005,我想獲取日期並從中獲取時間嗎?

任何人可以幫助我...我是新來的C#

這裏是我的查詢。

return "select Timein, Timeout from Attendance where E_ID = " + E_ID + " and Date = " + DateTime.Now.ToShortDateString(); 
+1

您的腳本很容易出現SQL注入http://en.wikipedia.org/wiki/SQL_injection – Curt 2012-08-09 11:43:27

+1

請使用[的SqlParameter(http://msdn.microsoft。 COM/EN-US /庫/ system.data.sqlclient.sqlparameter.aspx)。注意文檔中的示例。 – Reniuz 2012-08-09 11:45:28

+0

在日期字段u'r查詢sql日期時間格式或varchar? – chamara 2012-08-09 11:46:17

回答

1

使用SQL Server CONVERT函數的輸入Date參數轉換爲時間 更改您的查詢,以適應下面CONVERT功能

SQL查詢中的任何一個時間格式轉換爲HH:MM:SS :

select convert(varchar, <<dateparam>>, 108) 

SQL查詢時間格式轉換爲HH:MI:SS:MMM(24小時):

select convert(varchar, <<dateparam>>, 114) 
1

你應該總是使用參數查詢數據庫時 - SQL注入是否是可能的,這只是普通好的做法使用參數,它解決了一些棘手的報價多少和哪一種,我需要這裏也要使它成爲一個有效的SQL語句問題。

所以你可以試試:

string sqlStmt = "SELECT Timein, Timeout FROM dbo.Attendance " + 
       "WHERE E_ID = @ID AND Date = @Date"; 

using(SqlConnection conn = new SqlConnection("your-connection-string-here")) 
using(SqlCommand cmd = new SqlCommand(sqlStmt, conn)) 
{ 
    // set up parameters 
    cmd.Parameters.Add("@ID", SqlDbType.Int).Value = E_ID; 
    cmd.Parameters.Add("@Date", SqlDbType.DateTime).Value = DateTime.Now.Date; 

    // open connection, read data, close connection 
    conn.Open(); 

    using(SqlDataReader rdr = cmd.ExecuteReader()) 
    { 
     while(rdr.Read()) 
     { 
      // read your data 
     } 

     rdr.Close(); 
    } 

    conn.Close(); 
}