将多个值添加到SQL Server表

时间:2013-02-05 23:34:05

标签: c# sql sql-server winforms ado.net

首先,我想道歉,如果这不仅仅是一个例子,而是我真的迷失了。我有一个Windows窗体,从文本文件加载信息。在每个文本文件中,存在给定状态中的所有城市和县,每个部分由.Split分隔。我有一个SQL Server 2008数据库,2列,名称和类型。我想要做的是获取所有信息并将其添加到单个行中,名称列是名称,类型列是州或县。这是我如何拆分信息。如何为文本中的每个条目添加新行?

void PopulateZones()
{
    ofdFile.Filter = "Text File (.txt)|*.txt|All Files (*.*|*.*";
    ofdFile.FilterIndex = 1;
    ofdFile.Multiselect = true;

    ofdFile.FileName = String.Empty;
    if (ofdFile.ShowDialog() == DialogResult.OK)
    {
        ofdFileLocTextBox.Text = ofdFile.FileName.ToString();
        string groups = File.ReadAllText(ofdFile.FileName);
        string[] parts = groups.Split(new char[] { '*' }, StringSplitOptions.RemoveEmptyEntries);
        stateTextBox.Text = parts[0];
        citiesTextBox.Text = parts[1];
        countiesTextBox.Text = parts[2];
        AddtoSQL(parts[0], parts[1]);
    }
}

void AddtoSQL(string cities, string counties)
{
    Sqlconnection conn = new SqlConnection(connString)
    Sqlcommand comm = new Sqlcommand("INSERT into [Table] (Name, Type) Values (@Name, @Type))";
    comm.Parameters.Add(@Name, each line of textbox);
    comm.Parameters.Add(@Type, City or County);
    comm.ExecuteNonQuery();
}

3 个答案:

答案 0 :(得分:1)

所以,你遇到的第一个问题是你的代码没有做你认为它做的事情。最大的问题是你正在阅读所有文本,然后才选择它的前三个值。你不要给出数据的格式,但假设它看起来像这样:

Scotland*Edinburgh*Midlothian*
Scotland*Perth*Perthshire*

您的代码

string groups = File.ReadAllText(ofdFile.FileName);

将整个文件读入一个字符串,使其看起来像这样

Scotland*Edinburgh*Midlothian*\r\nScotland*Perth*Perthshire*

使用以下

分割它
string[] parts = groups.Split(new char[] { '*' }, 
         StringSplitOptions.RemoveEmptyEntries);

给你一个6个部分的字符串数组。从中插入多行是可行的,但不会很整齐。你可以更好地按行读取文本文件,然后遍历行数组,随后拆分每个行,然后将相关部分添加到SQL中。像

这样的东西
string[] lines = System.IO.File.ReadAllLines(ofdFile.FileName);
foreach (var line in lines)
{
    string[] parts = line.Split('*');
    AddtoSQL(parts[0], parts[1]);
}

应插入所有数据,但另外,如果您希望一次执行大量插入,我建议在SQL事务中包含这些插入。

我会指导您查看this MSDN article on the SqlTransaction Class

它的要点是首先声明一个事务,然后遍历执行那些事务的插入。最后,当您提交事务时,查询将全部写入数据库。我这样做的原因是它会更快更安全。

答案 1 :(得分:0)

如果将sql语句更改为“insert into [table](name,type)values(@name,@ type)”,它是否有效?用支架。

答案 2 :(得分:0)

在SQL Server 2008中,您可以使用一个查询插入多行(记录)。您需要做的就是提取行值并构造查询字符串的循环。因此,在AddToSQL方法中,请将您的查询设为:

INSERT INTO [Table](Name, Type)
VALUES ('First',State1),
('Second',State2),
('Third',State3),
('Fourth',State4),

Insert Multiple Records Using One Insert Statement