如何在for循环中选择值?

时间:2015-12-26 04:53:34

标签: c# selenium

我写程序获取代理。 我只获得要在此DataTable中插入的IP地址和端口。 像这样:

proxy_l {string[9]} string[]
[0] "IP Address"    string
[1] "Port"  string
[2] "Code"  string
[3] "All21134299883128312944344445555808080808180858118812881468888 AllUS AllUnited States Allanonymouselite 
[4] "52.8.219.180 80 US United States anonymous no yes 13 seconds ago"  string
[5] "158.69.88.81 80 US United States anonymous no no 1 minute ago" string
[6] "155.14.140.50 8080 US United States anonymous no yes 1 minute ago" string
[7] "23.244.68.94 80 US United States anonymous no no 1 minute ago" string
[8] "70.43.70.181 80 US United States anonymous no yes 1 minute ago"    string
[9] "165.139.149.169 3128 US United States elite proxy no yes 1 minute ago" string

这是我的代码:

var proxy_l = prx.FindElementById("proxylisttable").Text.Split(new string[] { "\r\n" }, StringSplitOptions.None);
for (int i = 0; i < proxy_l.Length; i++)
{
    if (proxy_l[i].ToString().ToLower().IndexOf("US") != -1)
    {
        var proxy_lc = proxy_l[i].Split(' ');c[1] + "',0)");
        mysql_db.query("insert into proxy_list(proxy_url,is_ssl) values('" + proxy_lc[0] + ":" + proxy_lc[1] + "',0)");
    }
}

我希望在数据库中插入时的结果如下:

 `IP`                `Port`

52.8.219.180 80

非常感谢。

1 个答案:

答案 0 :(得分:0)

首先,你的代码可以用于sql注入。所以我已将其更改为使用参数化查询。其次,我假设您的proxy_list表中包含名为&#39; IP&#39;和#&#39;港口&#39;这应该让你开始:

string[] proxy_l = prx.FindElementById("proxylisttable").Text.Split(new string[] { "\r\n" }, StringSplitOptions.None);

var proxyInfos = proxy_l
    .Where(l => l.Contains(" US "))
    .Select(l => l.Split(' '))
    .Select(tokens => new
    {
        IP = tokens[0],
        Port = tokens[1]
    })
    .ToList();

using (MySqlConnection cn = new MySqlConnection())
{
    foreach (var proxyInfo in proxyInfos) {
        using (MySqlCommand cm = cn.CreateCommand())
        {
            cm.CommandText = "insert into proxy_list(ip, port) values(@ip, @port);";
            cm.Parameters.AddWithValue("@ip", proxyInfo.IP);
            cm.Parameters.AddWithValue("@port", proxyInfo.Port);
            cm.ExecuteNonQuery();
        }
    }
}