How to pass mysql query and connection string and getting results?
I have a SQL connection string like this:
Data Source=myServerAddress;Initial Catalog=myDataBase;User Id=myUsername;Password=myPassword;
I have a query like this: stratdate = 10-03-2001, Enddate = 20-08-2008
str开发者_Python百科ing 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))
I don't know how to pass this query to database with connection string and getting the results into datatable. I'm doing WinForms applications with C# and using MySQL as database.
How can I do this? Would anyone have any idea about this? How can I pass this as a command text to MySQL? Would anyone help me with a sample code snippet?
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;
}
精彩评论