sql-server - 从 DGV 添加列到 SQL Server 的问题

标签 sql-server database vb.net datasource dataadapter

如果标题有点含糊,我很抱歉,但我不确定如何把它放在一个简短的空间中。

对于上下文,我有一个保存按钮,当所做的更改在 SQL 服务器数据库中更新时。这在添加行或更改值甚至删除行时效果很好。那里没有错。

但是,当我尝试添加或删除列时,应用程序会变得有点问题,并且不会更新数据库中添加/删除的列,也不会引发错误。

我可以添加或删除列的唯一方法是在添加/删除按钮上使用 sql 查询,但这会直接保存到服务器 - 我不想这样做。

我需要的是让更改出现在表中,然后仅在单击保存按钮时更新数据库。

我的代码在这里 ---(请注意,这是通过三种形式完成的,我有带表格的主形式,另外还有两个用于输入要添加的“培训师列”的名称或删除)

    Private Function save() ''''' Main form
    Try
        ds.Tables(0).AcceptChanges()
        da.Update(ds)
        DataTableColours()
        MessageBox.Show("Data updated successfully.")
    Catch
        MessageBox.Show("Data failed to update properly. Please ensure you are connected to the Baltic network and try again. If the problem persists, seek IT support.")
    End Try
End Function

Public Function AddTrainerFunc() ''''' Main form
    'Dim SqlAddCol As String = "ALTER TABLE MasterTrainerSchedule ADD [" & TrainerName.Trim() & "] nvarchar(255)"
    'Using con As New OleDbConnection(cs)
    '    Using cmd As New OleDbCommand(SqlAddCol, con)
    '        con.Open()
    '        cmd.ExecuteNonQuery()
    '    End Using
    'End Using

    ds.Tables(0).Columns.Add(TrainerName.Trim()).DefaultValue = " "
    RefreshBtn()
End Function

Public Function delTrainerFunc() ''''' Main form
    Dim SqlDelCol As String = "ALTER TABLE MasterTrainerSchedule DROP COLUMN [" & TrainerName.Trim() & "]"
    Using con As New OleDbConnection(cs)
        Using cmd As New OleDbCommand(SqlDelCol, con)
            con.Open()
            cmd.ExecuteNonQuery()
        End Using
    End Using
    ds.Tables(0).Columns.Remove(TrainerName)
    DelTrainer.Close()
    RefreshBtn()
    MessageBox.Show("Trainer '" & TrainerName.Trim() & "' has been deleted from the table.")
End Function

Private Sub btnAdd_Click(sender As Object, e As EventArgs) Handles btnAdd.Click '''''Add Column Form
    If Not txtTrainerName.Text = "Trainer Name Here" Or txtTrainerName.Text = "" Then
        MTS.TrainerName = txtTrainerName.Text
        MTS.Enabled = True
        Me.Close()
        MTS.AddTrainerFunc()
    Else
        MessageBox.Show("Please input a name for the trainer in the text box above.")
    End If
End Sub

Private Sub btnDel_Click(sender As Object, e As EventArgs) Handles btnDel.Click ''''' Delete Column form
    Dim delYN As Integer = MessageBox.Show("Are you sure you want to delete '" & cmbTrainers.Text & "' from the MTS table? The action will be permanent!", "Delete Trainer?", MessageBoxButtons.YesNo)
    If delYN = DialogResult.Yes Then
        MTS.Enabled = True
        MTS.delTrainerFunc()
    End If

End Sub

抱歉,如果这有点啰嗦但是......我似乎无法找到一种方法来将列添加到数据库中,这也是我想要的,既不是通过谷歌搜索答案,也不是通过简单的实验,所以我来了在此希望你们中的一个人能够提供帮助。提前感谢您提供的任何帮助。

编辑 --- 如果有帮助的话,我正在使用 oleDB 作为到 sql 的连接。

编辑 2 --- 这里有一些屏幕截图,以供您查看应用程序的可视化方面。

The add form being used. (with the main form in the background. Sorry I couldnt get that on its own - only allowed two links with 6 rep!)

And the delete trainer form. The dropdown lists everyone in the table for you, then prompts you when you click "delete"

编辑 3 --- 好吧,我知道 Sean 所讨论的规范化表可能会奏效,但它可能需要对所使用的服务器和程序进行相当大的更改。我设法找到了一种更简单的方法来实现此功能,即仅在对数据网格进行更改后调用 sql 查询以在保存时向表中添加或删除列。

以下是一些代码,以防有人感兴趣。它有点乱,可能可以稍微优化一下,但这无论如何对我有用。 ` 私有(private)函数 save()

    Try
        da.Update(ds)
        DataTableColours()
        MessageBox.Show("Data updated successfully.")
    Catch
        MessageBox.Show("Data failed to update properly. Please ensure you are connected to the Baltic network and try again. If the problem persists, seek IT support.")
    End Try

    'This section reads the SQL server for column names, and adds any that are listed in the DGV, but not the database. I know its a little messy but itll do.
    Dim columnnum As Integer = -1
    Dim columname As String
    For Each column In ds.Tables(0).Columns
        columnnum = columnnum + 1
        columname = dgvSchedule.Columns(columnnum).HeaderText
        If Not ds2.Tables(0).Columns.Contains(columname) Then
            MessageBox.Show("Table does not include " & columname)

            Dim SqlAddCol As String = "ALTER TABLE MasterTrainerSchedule ADD [" & columname.Trim() & "] nvarchar(255)"
            Using con As New OleDbConnection(cs)
                Using cmd As New OleDbCommand(SqlAddCol, con)
                    con.Open()
                    cmd.ExecuteNonQuery()
                End Using
            End Using

        End If
    Next

    columnnum = -1
    For Each column In ds2.Tables(0).Columns
        columnnum = columnnum + 1
        columname = ds2.Tables(0).Columns(columnnum).ColumnName
        If Not ds.Tables(0).Columns.Contains(columname) Then
            MessageBox.Show("Will Delete " & columname)

            Dim SqlDelCol As String = "ALTER TABLE MasterTrainerSchedule DROP COLUMN [" & columname.Trim() & "]"
            Using con As New OleDbConnection(cs)
                Using cmd As New OleDbCommand(SqlDelCol, con)
                    con.Open()
                    cmd.ExecuteNonQuery()
                End Using
            End Using
        End If
    Next

    ds2.Tables.Clear()
    da2 = New OleDbDataAdapter(sql, cs)
    da2.Fill(ds2)

End Function`

最佳答案

我不太了解您在这里所做的事情的很多细节,但这里有一个更规范化方法的示例。

create table Trainers
(
    TrainerID int identity 
    , FirstName varchar(25)
    , LastName varchar(25)
    , CONSTRAINT PK_Trainers PRIMARY KEY CLUSTERED (TrainerID)
)

create table Courses
(
    CourseID int identity 
    , CourseName varchar(50)
    , CONSTRAINT PK_Courses PRIMARY KEY CLUSTERED (CourseID)
)

create table TrainerCourses
(
    TrainerID int not null
    , CourseID int  not null
    , StartDate date not null
    , EndDate date not null
    , DailyStartTime time not null
    , CONSTRAINT PK_TrainerCourses PRIMARY KEY CLUSTERED (TrainerID, CourseID, StartDate, DailyStartTime)
    , CONSTRAINT FK_TrainerCourses_Trainers FOREIGN KEY (TrainerID) REFERENCES Trainers(TrainerID)
    , CONSTRAINT FK_TrainerCourses_Courses FOREIGN KEY (CourseID) REFERENCES Courses(CourseID)
)

关于sql-server - 从 DGV 添加列到 SQL Server 的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37726334/

相关文章:

sql-server - 如何将数据从 Excel 发送到 SQL 临时表以使用 VBA 进行处理?

database - 当从网页上抓取大量统计信息时,我应该多久将收集到的结果插入到数据库中?

javascript - 构建asp :chart dynamically using javascript

c# - 为什么我可以将索引器应用于 VB.Net 中的 ICollection,但不能在 C# 中

javascript - 如何下载网页组件?

sql-server - 仅使用脚本向导为触发器生成脚本

sql - 如何从另一台服务器访问我的数据库

sql - 当插入的值大于列长度时,插入到 SQL Server 表中的值不正确

mysql - Mysql中字段指向其他表字段

java - 如何为java中的许多方法建立一个数据库连接?