2011-09-07 59 views
0

我有一個SQL連接字符串是這樣的:如何傳遞mysql查詢和連接字符串並獲取結果?

Data Source=myServerAddress;Initial Catalog=myDataBase;User Id=myUsername;Password=myPassword; 

我有這樣的查詢:stratdate = 10-03-2001, Enddate = 20-08-2008

string sql = string.Format(@"SELECT CONCAT(UPPER(SUBSTRING(visit_Status, 1, 1)), SUBSTRING(visit_Status FROM 2)) as Status, COUNT('x') AS Visits 
           FROM visits 
           WHERE visit_Date BETWEEN '{0}' AND '{1}' 
           GROUP BY visit_Status", StartDate.ToString(dateFormat), EndDate.ToString(dateFormat)) 

我不知道如何將這種查詢傳遞到數據庫連接字符串和獲取結果導入數據表。我正在用C#做WinForms應用程序,並使用MySQL作爲數據庫。

我該怎麼做?有人會對此有任何想法嗎?我如何將這個命令文本傳遞給MySQL?有人會幫我一個示例代碼片段?

+0

我希望這篇文章能幫助.. http://www.codeproject.com/KB/database/DatabaseAcessWithAdoNet1.aspx – renil

+0

我怎麼能得到的數據到數據表不進dataset..would你請幫助.. – user933429

+0

Thanq renil ...爲您的支持.. – user933429

回答

1
public DataTable GetVisits(System.DateTime startDate, System.DateTime endData) 
{ 
    const string SQL = "SELECT CONCAT(UPPER(SUBSTRING(visit_Status, 1, 1)), SUBSTRING(visit_Status FROM 2)) as Status, COUNT('x') AS Visits FROM(visits) WHERE visit_Date BETWEEN @startDate AND @endData GROUP BY visit_Status"; 
    const string CONNSTR = "Data Source=myServerAddress;Initial Catalog=myDataBase;User Id=myUsername;Password=myPassword;"; 
    var tblVisits = new DataTable("Visits"); 
    using (var conn = new MySql.Data.MySqlClient.MySqlConnection(CONNSTR)) { 
     var cmd = new MySql.Data.MySqlClient.MySqlCommand(SQL, conn); 
     var da = new MySql.Data.MySqlClient.MySqlDataAdapter(cmd); 
     var param = new MySql.Data.MySqlClient.MySqlParameter("@startDate", MySql.Data.MySqlClient.MySqlDbType.Date); 
     param.Direction = ParameterDirection.Input; 
     param.Value = startDate; 
     cmd.Parameters.Add(param); 
     param = new MySql.Data.MySqlClient.MySqlParameter("@endDate", MySql.Data.MySqlClient.MySqlDbType.Date); 
     param.Direction = ParameterDirection.Input; 
     param.Value = endData; 
     cmd.Parameters.Add(param); 
     conn.Open(); 
     da.Fill(tblVisits); 
    } 

    return tblVisits; 
} 
+0

許多感謝添..現在它的工作... – user933429

+0

很高興我能幫上忙。我有點驚訝,因爲它沒有經過測試,並從VB.NET轉換(我的默認語言)。 –

相關問題