2017-04-15 161 views
-6

我想獲得所有數據按日期從日期時間選擇器搜索作爲我選擇的日期 我無法得到此查詢的結果 示例8/4/2017我希望僅結果日期和時間按日期從日期搜索數據庫日期

 MessageBox.Show("Date they start: " + monthCalendar1.SelectionEnd.ToString("dd/MM/yyyy")); 
     String date = monthCalendar1.SelectionEnd.ToString("dd/MM/yyyy"); 

     con.Open(); 
     SqlCommand cmd = con.CreateCommand(); 
     cmd.CommandType = CommandType.Text;//'%"+a+"%' 
     cmd.CommandText = "Select * from selectItems where [last_stock_date] Like'" + date+ "%'"; 
     cmd.ExecuteNonQuery(); 
     DataTable dt = new DataTable(); 
     SqlDataAdapter da = new SqlDataAdapter(cmd); 
     da.Fill(dt); 
     dataGridView1.DataSource = dt; 
     con.Close(); 

IT IS數據庫表一個SelectItems:
IT IS DATABASE TABLE SELECTITEMS

結果就是暗無天日:
RESULT NOTHING COMING

+0

那是什麼last_stock_date列(我希望有時間類型,而不是爲varchar)類型裏面?你在用什麼數據庫(我在猜sqlserver)?你是否收到任何錯誤信息(如果有,請指定)?將這些細節添加到您的問題中(您可能想要分解成句子) –

+0

last_stock_date是dbtime中的datetime ms sql server中沒有錯誤消息只是空白datagridview –

+0

而且如果它是DateTime,爲什麼要像搜索它那樣搜索它一個字符串?你有沒有聽說過參數化查詢? – Steve

回答

1

如果last_stock_date是DateTime列(並帶有時間信息),那麼您不要使用字符串在其上進行搜索。這絕不會返回任何有意義的東西

而是使用參數化的查詢與DateTime類型的兩個參數,一個用於下限(搜索到的日期的00:00)和一個用於上界(23:59:59.999)所搜索的日期的

DateTime init = monthCalendar1.SelectionEnd; 
DateTime finish = init.AddDays(1); 

con.Open(); 
SqlCommand cmd = con.CreateCommand(); 
cmd.CommandType = CommandType.Text; 
cmd.CommandText = @"Select * from selectItems 
        where [last_stock_date] >= @init 
        AND [last_stock_date] < @finish"; 
cmd.Parameters.Add("@init", SqlDbType.DateTime).Value = init; 
cmd.Parameters.Add("@finish", SqlDbType.DateTime).Value = finish; 

DataTable dt = new DataTable(); 
SqlDataAdapter da = new SqlDataAdapter(cmd); 
da.Fill(dt); 
dataGridView1.DataSource = dt; 
con.Close(); 

我也建議你把這段代碼(主要是連接)中使用的一次性物品using語句

+1

或添加一整天的完成日期,並檢查'last_stock_date <@ finish' –

+0

@HansKesting是的,可能更好 – Steve

+0

它只在03/4/2017從月日曆。 並顯示2017年4月4日的結果 –