0

我正在收集要存储在数据库表中的用户列表及其信息。我在 Microsoft SQL Server Management Studio 中设置了这个数据库。数据库的主键设置为自增。当列表中没有更多用户时,我需要结束循环。我在测试帐户中有两个有效用户,但是我目前只有一个用户。我会更好使用 asqlDataAdapter吗?

List<User> result = ims.ListUsers(req).ListUsersResult.Users;

SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["default"].ConnectionString);

for (int i = 1; i < result.Count(); i++)
{
    foreach (User user in result.Where(x => x.UserName.Contains('@')))
    {
        string sql = @"INSERT INTO UserInfo (UserID, UserName) VALUES (@UserID, @UserName)";

        using (SqlCommand command = new SqlCommand(sql, connection))
        {
            command.Parameters.AddWithValue("@UserID", i);
            command.Parameters.AddWithValue("@UserName", user.UserName);

            connection.Open();
            command.ExecuteNonQuery();
            connection.Close();
        }
    }
}
4

4 回答 4

3

我不明白为什么您需要外部for-loop来创建 ID,因为您不应该手动设置主键列。它会自动增加。完成后,您还应该始终关闭连接

这是完整的代码:

string sql = @"INSERT INTO UserInfo (UserName) VALUES (@UserName)";
using(var con = new SqlConnection(ConfigurationManager.ConnectionStrings["default"].ConnectionString))
using(var cmd = new SqlCommand(sql, con))
{
    con.Open();
    foreach(var user in result.Where(x => x.UserName.Contains('@')))
    {
        // you don't need to set the UserID when you've set made it an Identity column
        cmd.Parameters.AddWithValue("@UserName", user.UserName);
        cmd.ExecuteNonQuery();
    }
}
于 2012-12-07T15:45:44.173 回答
0

我认为您需要更换:

for (int i = 1; i < result.Count(); i++)

和:

for (int i = 0; i < result.Count(); i++)
于 2012-12-07T15:46:37.697 回答
0

你的问题是你有2个循环。您需要删除第一个 for 循环,而是在每次通过 foreach() 执行时增加一个 int 变量

您正在添加具有相同 UserID 的多个用户

int userID = 1

foreach (User user in result.Where(x => x.UserName.Contains('@')))
{
    // your code

    userID++;
}
于 2012-12-07T15:47:34.733 回答
0

您不需要更新自增字段,它将由 SQL 服务器自动计数。试试这个代码:

        List<User> result = ims.ListUsers(req).ListUsersResult.Users;

        SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["default"].ConnectionString);

        foreach (User user in result.Where(x => x.UserName.Contains('@')))
        {
            string sql = @"INSERT INTO UserInfo (UserName) VALUES (@UserName)";

            using (SqlCommand command = new SqlCommand(sql, connection))
            {
                command.Parameters.AddWithValue("@UserName", user.UserName);
                connection.Open();
                command.ExecuteNonQuery();
                connection.Close();
            }
        }
于 2012-12-07T15:55:09.310 回答