我有一个像这样的SQL连接字符串:
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 :(得分: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;
}