【问题标题】:How to pull data from sql, add columns to a row and insert it into another sql table? [closed]如何从sql中提取数据,将列添加到一行并将其插入另一个sql表? [关闭]
【发布时间】:2014-08-15 07:48:25
【问题描述】:

你好 StackOverflow 社区,

我正在尝试编写某种审计跟踪功能,它应该能够从 sql 中提取数据(只有一行),向该行添加三列,并将其插入另一个数据库表(审计跟踪表)。

看起来像这样:

逻辑:
1. SELECT * FROM 'Lace' WHERE 'macaddress' = @mac
2. 预先添加用户、操作和时间戳(以了解何时、哪个用户做了什么)
3.将修改后的行添加到LaceAudit表中。

程序如下所示:

using System;
using System.Collections;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;

public class Audit2
{
    private static string _connectionString = ConfigurationManager.ConnectionStrings["LaceDbConnectionString"].ConnectionString;

    public enum Action
    {
        Login = 0,
        NewImageInstall = 1,
        OldImageRollback = 2,
        LocalScriptUpdate = 3,
        LaceOffline = 4,
        LaceOnline = 5,
        NewLace = 6,
        NewDepartment = 7,
        NewModel = 8,
        AlterModel = 9,
        NewHardwareId = 10,
        AlterHardwareId = 11
    };

    public static void AddToLaceAudit(string user, Action action, string mac)
    {
        // Pull Data with MAC
        DataTable dataTable = GetDataOfLace(mac);

        // Add needed columns for the new table
        dataTable.Columns.Add("user", typeof(string));
        dataTable.Columns.Add("action", typeof(int));

        // Fill in values for the new columns


        // Insert DataTable with new values to database


    }

    private static DataTable GetDataOfLace(string mac)
    {
        using (SqlConnection connection = new SqlConnection(_connectionString))
        {
            DataTable _dataTable = new DataTable();

            string _query = "SELECT * FROM [Lace] WHERE [macaddress] = @mac";
            SqlCommand command = new SqlCommand(_query, connection);
            command.Parameters.AddWithValue("@mac", mac);
            connection.Open();

            SqlDataAdapter da = new SqlDataAdapter(command);
            da.Fill(_dataTable);
            connection.Close();
            da.Dispose();

            return _dataTable;
        }
    }
}

我现在如何向这些列添加值并使用数据库中的新值填充 DataTable? LaceAudit 表已经存在。我只需要添加修改后的行。

【问题讨论】:

  • WHERE [macaddress] = '@mac' 应该是 WHERE [macaddress] = @mac,否则您正在寻找 macaddress '@mac' 这解释了为什么 DataTable 仍然为空。
  • 是的,就像你说的那样。我的问题写错了
  • 除此之外,您还不清楚您要达到的目标。什么是属性,为什么不能在LaceAudit中插入记录?
  • 我需要在行前添加用户、操作和时间戳并将其插入到 LaceAudit 表中。我的问题是,我不知道如何将这三个属性(用户、操作和时间戳)添加到数据表对象中?

标签: c# sql asp.net sql-server datatable


【解决方案1】:

如果我理解您的问题,您想在数据表中添加 2 个附加列,然后获取修改后的行并使用 AddToLaceAudit() 将其添加到您的 LaceAudit 表中。因此,要预先添加(添加列),请执行以下操作:

_dataTable.Columns.Add("user", typeof(string));
_dataTable.Columns.Add("action", typeof(Action));

添加/修改行时会自动生成 sql 中的时间戳列,因此不需要将其添加为列。填写时参考这 2 个新列。然后,您可以简单地将 DataTable(或 DataRow 以确保只有 1 行)传递给 AddToLaceAudit()。修改 AddToLaceAudit 以期望 DataTable(或 DataRow)而不是 3 个单独的变量。

如果您说您不知道应该在这些列中添加什么,那就有点棘手了。如果您正在创建网站或 Web 应用程序,则通常使用 HttpContext.Current.User.Identity.Name 检索用户。至于动作,这取决于您可以从哪里检索用户执行的动作,因为它没有存储在 Lace 中。不确定我能不能帮你解决这个问题。至于上面解释的时间戳(在较新的版本中,现在是rowversion)。

更新

关于您最近的 cmets,您可以将您的值(您拥有的)分配给这样创建的新列:

_dataTable.Rows[0]["user"] = //your user value here
_dataTable.Rows[0]["action"] = //your action here

需要修改 AddToLaceAudit 以接受这样的 DataTable:

AddToLaceAudit(DataTable dt)

要更新 LaceAudit 表,我建议使用您的更新语句编写一个存储过程,并将必要的变量作为参数传递。仔细查看 LaceAudit 表,您不需要将“Action”作为 typeof(Action) 存储在 dataTable 中,而是作为“int”存储,因为这就是 LaceAudit 中使用的内容。

【讨论】:

  • 你没看错!从Lace 表中获取行后,我想为这两列添加用户和操作+数据(值)列。然后我想将修改后的行添加到LaceAudit 表中检索用户和操作不是问题,我得到了这两个值。
  • @ElSyr - 这个答案有效吗?如果是这样,请将其标记为答案(单击选票旁边的勾号)。如果您正在寻找更多信息,请告诉我。
  • 这是迄今为止最有帮助的答案。但我需要知道如何将值添加到行并将其输入到已经存在的 LaceAudit 表中。它应该很简单。我只想获得 1 行,向该行添加两个值并将其添加到另一个已经存在的表中。我认为数据表对象适合这个,但如果不是,请告诉我:)
  • _dataTable["user"] = //你的用户值在这里(不起作用)
  • @ElSyr 抱歉,忘记添加行索引。会更新
【解决方案2】:

您需要创建一个类。 (抱歉我不会用c#写)

Public Class AuditTrail

    Private m_Mac As String
    Public Property Mac() As String
        Get
            Return m_Mac
        End Get
        Set(ByVal value As String)
            m_Mac = value
        End Set
    End Property

    Private m_Action As Action
    Public Property Action() As Action
        Get
            Return m_Action
        End Get
        Set(ByVal value As Action)
            m_Action = value
        End Set
    End Property

    Private m_User As String
    Public Property User() As String
        Get
            Return m_User
        End Get
        Set(ByVal value As String)
            m_User= value
        End Set
    End Property

    /*Add more properties as needed*/

    Public Function Create() As String
        Dim Result As String
        Dim SqlCmdStr As String = ("INSERT INTO LaceAudit(user, action, mac) VALUES (@User, @Action, @Mac)")
        Using SqlConn As New SqlConnection(_ConnectionString)
            Using SqlCmd As New SqlCommand(SqlCmdStr, SqlConn)
                Try
                    SqlConn.Open()
                    With SqlCmd.Parameters
                        .Clear()
                        .AddWithValue("User", User)
                        .AddWithValue("Action", Action)
                        .AddWithValue("Mac", Action)
                    End With
                    SqlCmd.ExecuteNonQuery()
                    Result = "Audit record successfully logged."
                 Catch ex As Exception
                     Result = ex.Message
                 Finally
                     SqlConn.Close()
                     SqlCmd.Dispose()
                     SqlConn.Dispose()
                 End Try
                 Return Result
            End Using
        End Using
    End Function

End Class

在调用表单/模块上

实例化类,填充属性,调用创建函数。

Private Sub CreateAuditRecord()
    Using AuditRecord As New AuditTrail
        With AuditRecord
            .User = "The user"
            .Mac = "The mac of machine the user is using"
            .Action = "The action the user committed you want to log"
            MsgBox(.Create())
        End With
    End Using
End Sub

【讨论】:

  • 对不起,我不想手动添加值,因为我还有其他具有其他属性的表。该函数需要独立添加两列值。然后在不同的表中插入新行
【解决方案3】:

如果我对您的理解正确,您是否希望能够将所有数据插入到表格中,即使表格本身发生了变化? 您可以从表中选择一行,将其插入 DataTable,然后使用ColumnName property

【讨论】:

  • 是的,我希望能够添加这三个属性并将修改后的 DataTable 对象添加到 LaceAudit。它应该是动态的,因为我不仅有这张桌子
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-01-20
  • 2017-03-02
  • 2016-12-17
  • 2011-11-27
  • 1970-01-01
  • 2014-07-20
  • 2020-05-22
相关资源
最近更新 更多