SQL表中的数据添加和更新

时间:2011-10-15 14:22:49

标签: c# asp.net

我对SQLClient和所有人都很新,而且我的SQL表有问题..当我运行我的代码时,数据而不是更新,会将自己附加到表中已有的记录中。我的代码

SqlConnection conneciones = new SqlConnection(connectionString);
SqlCommand cmd;
conneciones.Open();
//put values into SQL DATABASE Table 1
for (int ok = 0; ok < CleanedURLlist.Length; ok++)
{
     cmd = new SqlCommand("insert into URL_Entries values('" + CleanedURLlist[ok] + "' , '" + DateTime.Now + "' , '" + leak + "' )", conneciones);
     cmd.ExecuteNonQuery();
}
conneciones.Dispose();

3 个答案:

答案 0 :(得分:0)

您正在使用INSERT功能,即“添加新记录”

如果您想要更新,则需要UPDATE功能

UPDATE tablename 
SET column1 = 'x', column2 = 'y' 
WHERE id = z

答案 1 :(得分:0)

看一下这些函数,希望您对更新,插入和删除函数有更好的理解。

使用asp.net和c#以及sql server数据库读取,插入,更新和删除记录的代码片段

  static void Read()
  {
    try
    {
      string connectionString =
            "server=.;" +
            "initial catalog=employee;" +
            "user id=sa;" +
            "password=sa123";
        using (SqlConnection conn =new SqlConnection(connectionString))
        {
            conn.Open();
            using (SqlCommand cmd = new SqlCommand("SELECT * FROM EmployeeDetails", conn))
            {
                SqlDataReader reader = cmd.ExecuteReader();

                if (reader.HasRows)
                {
                    while (reader.Read())
                    {
                        Console.WriteLine("Id = ", reader["Id"]);
                        Console.WriteLine("Name = ", reader["Name"]);
                        Console.WriteLine("Address = ", reader["Address"]);
                    }
                }

                reader.Close();
            }
        }
    }
    catch (SqlException ex)
    {
        //Log exception
        //Display Error message
    }
}

static void Insert()
{
    try
    {
        string connectionString =
            "server=.;" +
            "initial catalog=employee;" +
            "user id=sa;" +
            "password=sa123";
        using (SqlConnection conn =new SqlConnection(connectionString))
        {
            conn.Open();
            using (SqlCommand cmd = new SqlCommand("INSERT INTO EmployeeDetails VALUES(" +
                   "@Id, @Name, @Address)", conn))
            {
                cmd.Parameters.AddWithValue("@Id", 1);
                cmd.Parameters.AddWithValue("@Name", "Amal Hashim");
                cmd.Parameters.AddWithValue("@Address", "Bangalore");

                int rows = cmd.ExecuteNonQuery();

                //rows number of record got inserted
            }
        }
    }
    catch (SqlException ex)
    {
        //Log exception
        //Display Error message
    }
}

static void Update()
{
    try
    {
        string connectionString =
            "server=.;" +
            "initial catalog=employee;" +
            "user id=sa;" +
            "password=sa123";
        using (SqlConnection conn = ew SqlConnection(connectionString))
        {
            conn.Open();
            using (SqlCommand cmd =
            new SqlCommand("UPDATE EmployeeDetails SET Name=@NewName, Address=@NewAddress WHERE Id=@Id", conn))
            {
                cmd.Parameters.AddWithValue("@Id", 1);
                cmd.Parameters.AddWithValue("@Name", "Munna Hussain");
                cmd.Parameters.AddWithValue("@Address", "Kerala");

                int rows = cmd.ExecuteNonQuery();

                //rows number of record got updated
            }
        }
    }
    catch (SqlException ex)
    {
        //Log exception
        //Display Error message
    }
}

static void Delete()
{
    try
    {
        string connectionString =
            "server=.;" +
            "initial catalog=employee;" +
            "user id=sa;" +
            "password=sa123";
        using (SqlConnection conn = ew SqlConnection(connectionString))
        {
            conn.Open();
            using (SqlCommand cmd =
                new SqlCommand("DELETE FROM EmployeeDetails " +
                    "WHERE Id=@Id", conn))
            {
                cmd.Parameters.AddWithValue("@Id", 1);

                int rows = cmd.ExecuteNonQuery();

                //rows number of record got deleted
            }
        }
    }
    catch (SqlException ex)
    {
        //Log exception
        //Display Error message
    }
}

答案 2 :(得分:0)

您的代码应该插入新记录,但我不清楚它是否没有这样做,或者您的意思是更新现有记录。

除此之外,了解您是使用SQL Server的新手,您应该注意一些事项。

  1. 您应该使用using自动处理资源。这也将为您关闭您的连接,因此您没有闲置的开放连接。

  2. 您应该使用参数来防范sql injection攻击。在您的情况下使用参数的另一个好处是您不需要为每个语句创建新命令。

  3. 例如:

    using (var connection = new SqlConnection(connectionString)
    using (var command = connection.CreateCommand())
    {
        command.CommandText = "insert into URL_Entries values(@url, @now, @leak)";
    
        command.Parameters.AddWithValue("@now", DateTime.Now);
        command.Parameters.AddWithValue("@lead", leak);
    
        // update to correspond to your definition of the table column
        var urlParameter = command.Parameters.Add(new SqlParameter("@url", SqlDbType.VarChar, 100));
    
        connection.Open();
    
        for (int ok = 0; ok < CleanedURLlist.Length; ok++)
        {
            urlParameter.Value = CleanedURLlist[ok];
            command.ExecuteNonQuery();
        }
    }
    

    根据您的评论,如果您想进行更新,则需要包含标识要更新的行的参数。如果这是一行,请使用主键值:

    command.CommandText = "update URL_Entries set UrlColumn = @url, ModifiedDate = @now where ID = @id";