0

我有一个*.TXT大约 1 - 200 行的文件。每一行只是一个城市/郊区的名称,我试图将这个文件中的每一行插入到数据库中。

我把它全部放在一个 Try/Catch 块中,因为它不起作用,但是当我输出异常的详细信息时,什么也没有出现,如果有的话。

我已经确认我可以只用这一行一次插入 1 条记录:

db.Execute("insert into SuburbsPostCodesAndStates (Suburb, State) values (@0, @1)", "lol", "nsw");

我用来插入这些行的代码是:

@{
    var message = "";
    var db = Database.Open("SSSCCC");

    try
    {
        if(File.Exists(Href("~/NSW.txt")))
        {
            string[] text = File.ReadAllLines(Href("~/NSW.txt"));

            using (StringReader reader = new StringReader( text ))
            {
                string line;

                while ((line = reader.ReadLine()) != null)
                {
                    db.Execute("insert into SuburbsPostCodesAndStates (Suburb, State) values (@0, @1)", line, "NSW");
                }
            }
        }
    }
    catch(Exception exception)
    {
        message = exception.Message;
    }
}

<!DOCTYPE html>

<html lang="en">
    <head>
        <meta charset="utf-8" />
        <title></title>
    </head>
    <body>
        @message
    </body>
</html>

我该怎么办?

任何帮助都非常感谢。

谢谢

解决方案:

@{  
    var message = "";  
    var db = Database.Open("SSSCCC");  

    try  
    {  
        if(File.Exists(Server.MapPath("NSW.txt")))  
        {  
            string[] text = File.ReadAllLines(Server.MapPath("NSW.txt"));  

            if(text.Length == 0) { throw new Exception("File does not contain any lines"); }

            foreach(string line in text)  
            {  
                db.Execute("insert into SuburbsPostCodesAndStates (Suburb, State) values (@0, @1)", line, "NSW");  

            }  
        }  
        else 
        { 
          throw new Exception("File does not exist"); 
        } 
    }  
    catch(Exception exception)  
    {  
        message = exception.Message;  
    }  
}
4

1 回答 1

1

我不确定你为什么在这里使用 StringReader ......试试这个。

@{ 
          var message = ""; 
    var db = Database.Open("SSSCCC"); 
    try 
    { 
        if(File.Exists(Server.MapPath("~/NSW.txt"))) 
        { 
            string[] text = File.ReadAllLines(Server.MapPath("~/NSW.txt")); 
            if(text.Length == 0) throw new Exception("File does not contain any lines");
            foreach(string line in text) 
            { 
                db.Execute("insert into SuburbsPostCodesAndStates (Suburb, State) values (@0, @1)", line, "NSW"); 

            } 
        } 
        else
        {
          throw new Exception("File does not exist");
        }
    } 
    catch(Exception exception) 
    { 
        message = exception.Message; 

    } 
} 
于 2012-05-20T13:50:49.893 回答