【发布时间】:2021-12-27 19:52:53
【问题描述】:
我正在编写一个 C# windows 应用程序来更新 WordPress 中使用的自定义 MySQL 数据库。我想要做的是将连接字符串放在一个地方。例如,我包含了我准备将所有内容切换到存储生产者的测试代码。我在网上找了一个很好的例子,或者我做错了什么
public void FindURL()
{
string connStr = "server=127.0.0.1;user=root;database=mypocket;port=3306;password=";
MySqlConnection conn = new MySqlConnection(connStr);
conn.Open();
try
{
MySqlCommand cmd = new MySqlCommand("select id, fullname from siteinfo where Site_Url like '%" + txtURLInput.Text + "%'", conn);
MySqlDataReader reader = cmd.ExecuteReader();
bool hasRecords = false;
while (reader.Read())
{
}
if (!hasRecords)
{
}
}
catch (Exception ex)
{
MessageBox.Show("Error Getting Records" + ex.ToString());
}
}
public void FindName()
{
string connStr = "server=127.0.0.1;user=root;database=mypocket;port=3306;password=";
MySqlConnection conn = new MySqlConnection(connStr);
conn.Open();
txtNameOutput.Text = "";
try
{
MySqlCommand cmd = new MySqlCommand("select id, fullname from siteinfo where fullname like '%" + txtCheckName.Text + "%'", conn);
MySqlDataReader reader = cmd.ExecuteReader();
bool hasRecords = false;
while (reader.Read())
{
}
if (!hasRecords)
{
txtNameOutput.Text = "Not Found";
}
}
catch (Exception ex)
{
MessageBox.Show("Error Getting Records" + ex.ToString());
}
}
【问题讨论】:
-
为什么不把连接字符串放在配置文件中呢? docs.microsoft.com/en-us/troubleshoot/dotnet/csharp/…
-
谢谢它工作得很好。
-
您的代码容易受到 SQL 注入攻击。请使用参数化查询。