C# 从MySQL表接收下行链接
我尝试在MySQL表中搜索ID并返回包含URL的相关字符串列。 但是下载程序总是告诉我链接格式是错误的 这是我的方法:C# 从MySQL表接收下行链接,c#,mysql,.net,webclient-download,C#,Mysql,.net,Webclient Download,我尝试在MySQL表中搜索ID并返回包含URL的相关字符串列。 但是下载程序总是告诉我链接格式是错误的 这是我的方法: public string URL(string ID) { MySqlConnection con = new MySqlConnection("host=localhost;user=root;password=root;database=Downloader;"); MySqlCommand cmd = new MySq
public string URL(string ID)
{
MySqlConnection con = new MySqlConnection("host=localhost;user=root;password=root;database=Downloader;");
MySqlCommand cmd = new MySqlCommand("SELECT string FROM Files WHERE ID = '" + ID + "';");
cmd.Connection = con;
con.Open();
MySqlDataReader reader = cmd.ExecuteReader();
return reader.ToString();
}
这里是下载程序:
private void button1_Click(object sender, EventArgs e)
{
sql_reader sql_reader = new sql_reader();
if (!Directory.Exists("Downloads"));
{
Directory.CreateDirectory("Downloads");
}
WebClient client = new WebClient();
client.DownloadProgressChanged += new DownloadProgressChangedEventHandler(client_DownloadProgressChanged);
client.DownloadFileCompleted += new AsyncCompletedEventHandler(client_DownloadFileCompleted);
client.DownloadFileAsync(new Uri(sql_reader.URL(textBox1.Text)), "./Downloads/" + textBox2.Text + "." + textBox3.Text);
textBox1是我输入ID的框。1。在从
MySqlDataReader
对象获取记录之前,需要调用Read()
函数
2。访问记录时,必须指定列名
例如:
String result="";
MySqlDataReader reader = cmd.ExecuteReader();
if(reader.Read())
result=reader["columnname"].ToString();
MySqlCommand cmd = new MySqlCommand("SELECT string FROM Files WHERE ID =@ID;");
cmd.Parameters.AddWithValue("@ID",ID);
3.我建议您使用参数化查询
来避免SQL注入攻击
例如:
String result="";
MySqlDataReader reader = cmd.ExecuteReader();
if(reader.Read())
result=reader["columnname"].ToString();
MySqlCommand cmd = new MySqlCommand("SELECT string FROM Files WHERE ID =@ID;");
cmd.Parameters.AddWithValue("@ID",ID);
4.dipose
正确地使用MySqlCommand
、MySqlConnection
和MySqlDataReader
对象。您可以使用using{}
block来干净地使用它们
完整代码
public string URL(string ID)
{
String result="";
using(MySqlConnection con = new MySqlConnection("host=localhost;user=root;password=root;database=Downloader;"))
{
using(MySqlCommand cmd = new MySqlCommand("SELECT string FROM Files WHERE ID =@ID;"))
{
cmd.Connection = con;
con.Open();
cmd.Parameters.AddWithValue("@ID",ID);
using(MySqlDataReader reader = cmd.ExecuteReader())
{
if(reader.Read())
result=reader["string"].ToString();
else
result="";//you can customize here
}
}
}
return result;
}
解决方案2:
替换此声明:
client.DownloadFileAsync(new Uri(sql_reader.URL(textBox1.Text)), "./Downloads/" + textBox2.Text + "." + textBox3.Text);
为此:
client.DownloadFileAsync(new Uri(sql_reader.URL(textBox1.Text),UriKind.Absolute), "./Downloads/" + textBox2.Text + "." + textBox3.Text);
现在我做了你发布的方法(顺便说一句,它在一个叫做“sql_reader”的单独类中),但我不知道如何做这个语法?@user3051872:你现在能运行代码了吗?只需在我的回答中将URL()
函数替换为URL()
函数即可。它工作得非常完美。相同的错误:无效的URI:URI方案无效。ID为abcdefg12345,应返回127.0.0.1/test。html@user3051872:您从URL()
函数中获得的URL,请调试并告知我。@user3051872:在URL()
函数中设置断点,并查看函数末尾的状态变量值。