[英]Read from txt file and write it to database
这是代码...代码都可以,但它只制作txt文件,而我想在读取txt文件并将其保存在数据库中时制作它...请帮我
static void Main(string[] args)
{
McdonaldScrapper();
//PizzaHutScrapper();
//KFCScrapper();
}
private static void McdonaldScrapper()
{
try
{
MatchCollection mcl;
WebClient webClient = new WebClient();
string strUrl = "http://www.mcdonalds.com.pk/products/view/menu-pricelist";
byte[] reqHTML;
reqHTML = webClient.DownloadData(strUrl);
UTF8Encoding objUTF8 = new UTF8Encoding();
string pageContent = objUTF8.GetString(reqHTML);
int index = pageContent.IndexOf("<div id=\"BodyText\">");
pageContent = pageContent.Substring(index);
Regex r = new Regex(@"(<td .*?</td>)");
mcl = r.Matches(pageContent);
int count = 0;
StringBuilder strBuilder = new StringBuilder();
string name = "";
string price = "";
foreach (Match ml in mcl)
{
string updatedString = ml.Value.Remove(ml.Value.IndexOf("</td>"));
if (count % 2 == 0)
{
name = updatedString.Remove(0, updatedString.IndexOf('>') + 1);
}
else
{
price = updatedString.Remove(0, updatedString.IndexOf('>') + 1);
strBuilder.Append(name + " , " + price + "\r\n");
}
count++;
}
File.WriteAllText(@"E:\McdonaldsMenu.txt", strBuilder.ToString().Replace("<br />", "").Replace("&", "").Replace(" ", ""));
SaveMcdonaldsMenuToDB();
Console.WriteLine("Press any key to continue");
Console.ReadKey();
}
catch (Exception ex)
{ }
}
private static void SaveMcdonaldsMenuToDB()
{
try
{
int counter = 0;
string line;
System.IO.StreamReader file = new System.IO.StreamReader("E:\\McdonaldsMenu.txt");
Dictionary<string, string> menuAndPriceList = new Dictionary<string, string>();
while ((line = file.ReadLine()) != null)
{
if (!menuAndPriceList.ContainsKey(line.Split(',')[0].Trim()))
{
menuAndPriceList.Add(line.Split(',')[0].Trim(), line.Split(',')[1].Trim());
counter++;
}
}
file.Close();
SqlConnection myConnection = new SqlConnection();
string Constr = @"Data Source=Samsung;Initial Catalog=MAAK FYP; Integrated Security=True";
myConnection = new SqlConnection(Constr);
myConnection.Open();
// SqlCommand cmd = new SqlCommand ("");
// SqlCommand cmd = new SqlCommand("INSERT into Table33(Product_Name,Product_Price) values(menuAndPriceList[i].key,menuAndPriceList[i].Value)");
for(int i=0; i<menuAndPriceList.Count; i++)
{
SqlCommand cmd = new SqlCommand("INSERT into Table33(Product_Name,Product_Price) values(menuAndPriceList[i].key,menuAndPriceList[i].Value)");
}
Console.ReadLine();
}
catch (Exception ex)
{ }
}
您从不执行插入命令,而必须执行cmd.ExecuteNonQuery();
或类似的东西。
而且,没有将参数传递给命令,而是导致语法错误。 使用此代替:
SqlCommand cmd = new SqlCommand("INSERT into Table33(Product_Name,Product_Price) values(@name, @price)");
cmd.Parameters.AddWithValue("@name", menuAndPriceList[i].key);
cmd.Parameters.AddWithValue("@price", menuAndPriceList[i].Value);
cmd.ExecuteNonQuery();
作为另一个说明,不要对捕获的异常执行任何操作就捕获所有异常。 查看抛出的异常,将其记录下来,否则您不知道出了什么问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.