这是代码......它的所有代码都没问题,但它只是制作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)
{ }
}
答案 0 :(得分:6)
您永远不会执行insert命令,您必须执行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();
作为另一个旁注,如果不对捕获的异常做任何事情,请不要捕获所有异常。看看抛出的异常,记录它们,否则你不知道出了什么问题。