我正在尝试将 SQL 连接从使用 MySql.Data 更改为使用 Dapper 从 VPS 上运行的 MySQL 数据库检索数据。我使用 MySql.Data 连接以下连接类没有问题
class Connection
{
MySqlConnection conn;
static string host = "Fake Name";
static string database = "Fake Database";
static string userDB = "Fake User";
static string password = "Fake Password";
public bool Open()
{
try
{
strProvider = "Server=" + host + ";Database=" + database + ";User ID=" + userDB + ";Password=" + password;
conn = new MySqlConnection(strProvider);
conn.Open();
return true;
}
catch (Exception er)
{
MessageBox.Show("Connection Error ! " + er.Message, "Information");
}
return false;
}
public void Close()
{
conn.Close();
conn.Dispose();
}
public DataSet ExecuteDataSet(string sql)
{
try
{
DataSet ds = new DataSet();
MySqlDataAdapter da = new MySqlDataAdapter(sql, conn);
da.Fill(ds, "result");
return ds;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
return null;
}
public MySqlDataReader ExecuteReader(string sql)
{
try
{
MySqlDataReader reader;
MySqlCommand cmd = new MySqlCommand(sql, conn);
reader = cmd.ExecuteReader();
return reader;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
return null;
}
public int ExecuteNonQuery(string sql)
{
try
{
int affected;
MySqlTransaction mytransaction = conn.BeginTransaction();
MySqlCommand cmd = conn.CreateCommand();
cmd.CommandText = sql;
affected = cmd.ExecuteNonQuery();
mytransaction.Commit();
return affected;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
return -1;
}
}
但是我正在尝试切换到 Dapper,以便我可以安全地管理查询。我正在使用下面的代码
DataAccess db = new DataAccess();
bookingList = db.GetBookings(BookingCalendar.SelectionStart.ToString("yyyy-MM-dd"));
public class DataAccess
{
public List<Booking> GetBookings(string date)
{
using (IDbConnection connection = new System.Data.SqlClient.SqlConnection(Helper.connectionString("Fake Name")))
{
return connection.Query<Booking>($"select * from Bookings WHERE Date ='{date}'").ToList();
}
}
}
public static class Helper
{
public static string connectionString(string name)
{
return ConfigurationManager.ConnectionStrings[name].ConnectionString;
}
}
<connectionStrings>
<add name="Fake Name" connectionString="Server=Fake IP; Database=Fake Database; User Id=Fake User; Password=Fake Password providerName=System.Data.SqlClient"/>
</connectionStrings>
但在尝试打开连接时,15 秒后出现路径未找到错误。我不确定为什么会发生这种情况,因为这两个连接字符串是相同的。任何对此的帮助将不胜感激
当然这是行不通的。您在第二个代码片段中使用了
SqlClient
,这是特定于 SQL Server 的。如果您想连接到 MySQL,那么您仍然需要使用 MySQL 提供程序。