我尝试在MySQL表中搜索ID,然后返回包含URL的关联字符串列。
但是下载器总是告诉我链接格式是错误的。
这是我的方法:
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的Box。
最佳答案
1.您需要先调用Read()
函数,然后再从MySqlDataReader
对象获取记录
2.您必须在访问记录时指定column name
。
例:
String result="";
MySqlDataReader reader = cmd.ExecuteReader();
if(reader.Read())
result=reader["columnname"].ToString();
3.我建议您使用
Parametrised Queries
来避免SQL injection Attacks
。例:
MySqlCommand cmd = new MySqlCommand("SELECT string FROM Files WHERE ID =@ID;");
cmd.Parameters.AddWithValue("@ID",ID);
4.正确
dipose
MySqlCommand
,MySqlConnection
和MySqlDataReader
对象。您可以使用using{}
块将它们干净地处置。完整的代码
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);