逐行插入SQL Server CE数据库

时间:2012-05-20 13:45:11

标签: c# razor sql-server-ce webmatrix

我的*.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;  
    }  
}

1 个答案:

答案 0 :(得分: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; 

    } 
}