数据库仅更新具有不同值C#的第一行

时间:2014-07-24 07:59:48

标签: c# sql xml database sql-server-2008

        string connetionString = null;
        SqlConnection connection;
        SqlCommand command;
        SqlDataAdapter adpter = new SqlDataAdapter();
        DataSet ds = new DataSet();
        XmlReader xmlFile;
        string sql = null;

        int ID = 0;
        string Name = null, Text = null, Screenname = null;


        connetionString = "myconnection";

        connection = new SqlConnection(connetionString);

        xmlFile = XmlReader.Create("my.XML", new XmlReaderSettings());
        ds.ReadXml(xmlFile);
        int i = 0;
        connection.Open();
        for (i = 0; i <= ds.Tables[0].Rows.Count - 1; i++)
        {
            ID = Convert.ToInt32(ds.Tables[0].Rows[i].ItemArray[0]);
            Text = ds.Tables[0].Rows[i].ItemArray[1].ToString().Replace("'", "''");
            Name = ds.Tables[0].Rows[i].ItemArray[2].ToString().Replace("'", "''");
            Screenname = ds.Tables[0].Rows[i].ItemArray[3].ToString().Replace("'", "''");

            //sql = "insert into nicktest values(" + ID + ",'" + Text + "'," + Name + "," + Screenname + "," + DateTime.Now.ToString() + ")";
            sql = "If Exists(Select * from niktest2 Where Id  = ID) " +
                                        " BEGIN " +
                                        " update niktest2 set Name  = '" + Text + "' , Screenname = '" + Name + "', Profimg= '" + Screenname + "', InsertDateTime= '" + DateTime.Now.ToString() + "' where Id=ID" +
                                        " END " +
                                        " ELSE " +
                                        " BEGIN " +
                                        " insert into niktest2(Id,Name,Screenname,Profimg,InsertDateTime) values('" + ID + "','" + Text + "','" + Name + "','" + Screenname + "' ,'" + DateTime.Now.ToString() + "')" +
                                        " END ";
            command = new SqlCommand(sql, connection);
            adpter.InsertCommand = command;
            adpter.InsertCommand.ExecuteNonQuery();
        }
    }

运行此代码后,即使我的xml文件有更多数据,第一行也会更新。 我想将所有数据插入到数据库中,并在xml文件中为其分配id。 请帮忙..

1 个答案:

答案 0 :(得分:4)

只要插入一行,就会出现这种情况:

If Exists(Select * from niktest2 Where Id  = ID)

因此,您将执行更新,而不是插入,因此您只能在数据库中获得一行。

由于您使用的是SQL Server 2008,我会采用完全不同的方法,使用Parameterised queriesMERGEtable valued parameters

第一步是创建表值参数(我不得不猜测你的类型:

CREATE TYPE dbo.nicktestTableType AS TABLE
(   
    Id INT,
    Name VARCHAR(255),
    Screenname VARCHAR(255),
    Profimg VARCHAR(255)
);

然后,您可以编写MERGE语句以插入数据库:

MERGE nicktest WITH (HOLDLOCK) AS t
USING @NickTestType AS s
    ON s.ID = t.ID
WHEN MATCHED THEN 
    UPDATE
    SET Name = s.Name,
        Screenname = s.Screenname,
        Profimg = s.Profimg,
        InsertDateTime = GETDATE()
WHEN NOT MATCHED THEN 
    INSERT (Id, Name, Screenname, Profimg, InsertDateTime)
    VALUES (s.Id, s.Name, s.Screenname, s.Profimg, GETDATE());

然后,您可以将数据表作为参数传递给查询:

using (var command = new SqlCommand(sql, connection))
{
    var parameter = new SqlParameter("@NickTestType", SqlDbType.Structured);
    parameter.Value = ds.Tables[0];
    parameter.TypeName = "dbo.nicktestTableType";
    command.Parameters.Add(parameter);
    command.ExecuteNonQuery();
}

如果您不想做出如此大的改动,那么您至少应该使用参数化查询,因此您的SQL将是:

IF EXISTS (SELECT 1 FROM nicktest WHERE ID = @ID)
BEGIN
    UPDATE  nicktest
    SET     Name = @Name,
            ScreenName = @ScreeName,
            InsertDateTime = GETDATE()
    WHERE   ID = @ID;
END
ELSE
BEGIN
    INSERT (Id, Name, Screenname, Profimg, InsertDateTime)
    VALUES (@ID, @Name, @Screenname, @Profimg, GETDATE());
END

或者最好仍然使用MERGE作为HOLDLOCK表提示阻止(或至少大大降低了)race condition的可能性:

MERGE nicktest WITH (HOLDLOCK) AS t
USING (VALUES (@ID, @Name, @ScreenName, @ProfImg)) AS s (ID, Name, ScreenName, ProfImg)
    ON s.ID = t.ID
WHEN MATCHED THEN 
    UPDATE
    SET Name = s.Name,
        Screenname = s.Screenname,
        Profimg = s.Profimg,
        InsertDateTime = GETDATE()
WHEN NOT MATCHED THEN 
    INSERT (Id, Name, Screenname, Profimg, InsertDateTime)
    VALUES (s.Id, s.Name, s.Screenname, s.Profimg, GETDATE());

虽然使用表值参数,但效率远低于第一种解决方案 然后你的c#会是这样的:

for (i = 0; i <= ds.Tables[0].Rows.Count - 1; i++)
{
    using (var command = new SqlCommand(sql, connection))
    {
        command.Parameters.AddWithValue("@ID", ds.Tables[0].Rows[i][0]);
        command.Parameters.AddWithValue("@Name", ds.Tables[0].Rows[i][1]);
        command.Parameters.AddWithValue("@ScreeName", ds.Tables[0].Rows[i][2]);
        command.Parameters.AddWithValue("@ProfImg", ds.Tables[0].Rows[i][3]);
        command.ExecuteNonQuery();
    }
}