在Windows应用程序中使用SQL更新过程进行批量数据更新。

huangapple go评论76阅读模式
英文:

Bulk Data update in a windows application using SQL update procedure

问题

I've created a windows application to display the data from SQL database to a gridview in a windows application. I used VB.net and SQL server to do that. While using where condition in the sql query I got the values which satisfies given data. Now I need to update the shown data. For that I used the sql query Update columnName = value where (the condition). the column name and value are got from the user using a textbox. When i used the query in Sql, it works fine and the value gets updated in database. But, When I run the same in VB code it doesn't gets updated in the windows application. I doesn't get it, and the assigned time for it runs beyond my watch time. Please, help me someone. Thanks in advance.Here I attach the code.

英文:

I've created a windows application to display the data from SQL database to a gridview in a windows application. I used VB.net and SQL server to do that. While using where condition in the sql query I got the values which satisfies given data. Now I need to update the shown data. For that I used the sql query Update columnName = value where (the condition). the column name and value are got from the user using a textbox. When i used the query in Sql, it works fine and the value gets updated in database. But, When I run the same in VB code it doesn't gets updated in the windows application. I doesn't get it, and the assigned time for it runs beyond my watch time. Please, help me someone. Thanks in advance.Here I attach the code.

\ the code starts here \

Private Sub Btn_Edit_Click(sender As Object, e As EventArgs) Handles btn_Update.Click
        cmdupdate.Connection = connection
        connection.Open()
        'table.Rows.Clear()
        'table.Columns.Clear()
       
 cmdupdate.CommandText = "update tblWebaccessErrorTrack set @columnName = @editData where IssueDateTime between @frmdate and @todate and ErrorDetails like '%' + @errorDetails + '%' and  ClientIpaddress like '%'+ @IpAddress + '%' and ResponseStatus like '%'+ @responseStatus + '%' and TicketNo like '%' + @ticketNo + '%' select * from tblWebaccessErrorTrack"
        table.Clear()
        '"UPDATE tblWebaccessErrorTrack
        ' SET
        ' @columnName = @editData"
        '"sp_Updatedata"
        'Update tblWebaccessErrorTrack set TicketNo=202010 select * from tblWebaccessErrorTrack

        'cmdupdate.CommandType = CommandType.StoredProcedure
        cmdupdate.Parameters.Add("@frmdate", SqlDbType.DateTime).Value = frm_DateTimePicker.Text
        cmdupdate.Parameters.Add("@todate", SqlDbType.DateTime).Value = to_DateTimePicker.Text
        cmdupdate.Parameters.Add("@errorDetails", SqlDbType.NVarChar).Value = txtErrorDetails.Text
        cmdupdate.Parameters.Add("@IpAddress", SqlDbType.NVarChar).Value = txtClientIp.Text
        cmdupdate.Parameters.Add("@responseStatus", SqlDbType.NVarChar).Value = txtResponseStatus.Text
        cmdupdate.Parameters.Add("@ticketNo", SqlDbType.NVarChar).Value = txtTicketNo.Text
        cmdupdate.Parameters.Add("@columnName", SqlDbType.NVarChar).Value = Columnvalue '//column name
        cmdupdate.Parameters.Add("@editData", SqlDbType.NVarChar).Value = txtEditdata.Text '//Data we give

        adapter = New SqlDataAdapter(cmdupdate)

        adapter.Fill(table)
        adapter.Update(table)
        DataGridView1.DataSource = table
        'adapter.Fill(table)
        'table.Clear()


        'cmdupdate.CommandText = "select * from tblWebaccessErrorTrack" 'where IssueDateTime between @frmdate and @todate and ErrorDetails like '%' + @errorDetails + '%' and  ClientIpaddress like '%'+ @IpAddress + '%' and ResponseStatus like '%'+ @responseStatus + '%' and TicketNo like '%' + @ticketNo + '%'"
        'adapter = New SqlDataAdapter(cmdupdate)
        'adapter.Fill(table)
        'adapter.Update(table)
        'DataGridView1.DataSource = table
        ''adapter.Fill(table)
        ''cmdupdate.Parameters.Clear()
        'table.Clear()
        connection.Close()
        cmd.Parameters.Clear()

    End Sub`enter code here`
  • the character(') present in front of some line represents commented line.

答案1

得分: 1

以下是翻译的内容:

"如果将代码拆分成较小的部分,每个部分都执行一个任务,将会更容易。这样做可以使代码的理解和更新变得更简单。因此,更新列和显示DGV的方法应分开。

对于SQL,请注意,将SQL连接仅限于重复使用是一个不好的做法。有一种称为连接池的机制内置在其中,使运行查询的正确方式变得简单:创建连接,使用连接,处理连接。

如果要在SQL查询中使用变量作为列名,则必须将其连接到SQL查询中。这容易受到SQL注入的影响,因此在执行任何操作之前必须验证正在使用的列名是否有效。

对于DateTimePickers,要使用的值是.Value,而不是.Text,否则可能会与不同的Windows设置/区域设置产生问题。

因此,这段代码是使其工作的起点:

Private Function IsValidColumnName(colName As String) As Boolean
	'TODO: 将有效的列名放入数组中
	Dim validColumnNames = {"Col1", "Col2", "ColWhatever"}
	Return validColumnNames.Any(Function(c) colName = c)

End Function

Private Sub UpdateDataInColumn(columnName As String, newData As String)
	If Not IsValidColumnName(columnName) Then
		Throw New Exception("无效的列名 [" & columnName & "]")
	End If

	Dim sql = "UPDATE tblWebaccessErrorTrack SET [" & columnName & "] & = @editData WHERE IssueDateTime BETWEEN @frmdate AND @todate AND ErrorDetails LIKE @errorDetails AND ClientIpaddress LIKE @IpAddress AND ResponseStatus LIKE @responseStatus AND TicketNo LIKE @ticketNo"

	Using conn As New SqlConnection("Your connection string"),
			cmdupdate As New SqlCommand(sql, conn)

		cmdupdate.Parameters.Add("@frmdate", SqlDbType.DateTime).Value = frm_DateTimePicker.Value
		cmdupdate.Parameters.Add("@todate", SqlDbType.DateTime).Value = to_DateTimePicker.Value
		cmdupdate.Parameters.Add("@errorDetails", SqlDbType.NVarChar).Value = "%" + txtErrorDetails.Text & "%"
		cmdupdate.Parameters.Add("@IpAddress", SqlDbType.NVarChar).Value = "%" + txtClientIp.Text & "%"
		cmdupdate.Parameters.Add("@responseStatus", SqlDbType.NVarChar).Value = "%" + txtResponseStatus.Text & "%"
		cmdupdate.Parameters.Add("@ticketNo", SqlDbType.NVarChar).Value = "%" + txtTicketNo.Text & "%"
		cmdupdate.Parameters.Add("@editData", SqlDbType.NVarChar).Value = newData '//我们提供的数据

		Dim nChanged = cmdupdate.ExecuteNonQuery()

		If nChanged > 1 Then
			' 更新了多于一行这可能是一个大问题
		End If

	End Using

End Sub

Private Sub ShowDataGridView()
	'TODO: 编写ShowDataGridView()子程序
End Sub

Private Sub btn_Update_Click(sender As Object, e As EventArgs) Handles btn_Update.Click
	Dim colName = "在此处选择列的某种方法"
	Dim newData = txtEditdata.Text

	UpdateDataInColumn(colName, newData)
	ShowDataGridView()

End Sub

希望这有助于您的项目!

英文:

It will be easier if the code is split up into smaller pieces which each do one thing. It makes understanding and updating the code simpler. So, the methods to update a column and show the DGV would be separate.

For the SQL, please note that it is a bad idea to have just one SQL connection that gets re-used. There is a mechanism called connection pooling built in which makes the correct way of running a query a simple: create connection, use connection, dispose of the connection.

If you want to use a variable for the column name, then you have to concatenate it into the SQL query. This is open to SQL injection, so it is necessary to verify that a valid column name is being used before doing anything with it.

For the DateTimePickers, the value to use is the .Value, not the .Text, otherwise it could have problems with different Windows settings/locale.

So, this code is a starting point for getting it to work:

Private Function IsValidColumnName(colName As String) As Boolean
	'TODO: Put the valid column names in the array.
	Dim validColumnNames = {"Col1", "Col2", "ColWhatever"}
	Return validColumnNames.Any(Function(c) colName = c)

End Function

Private Sub UpdateDataInColumn(columnName As String, newData As String)
	If Not IsValidColumnName(columnName) Then
		Throw New Exception("Invalid column name [" & columnName & "]")
	End If

	Dim sql = "UPDATE tblWebaccessErrorTrack SET [" & columnName & "] & = @editData WHERE IssueDateTime BETWEEN @frmdate AND @todate AND ErrorDetails LIKE @errorDetails AND ClientIpaddress LIKE @IpAddress AND ResponseStatus LIKE @responseStatus AND TicketNo LIKE @ticketNo"

	Using conn As New SqlConnection("Your connection string"),
			cmdupdate As New SqlCommand(sql, conn)

		cmdupdate.Parameters.Add("@frmdate", SqlDbType.DateTime).Value = frm_DateTimePicker.Value
		cmdupdate.Parameters.Add("@todate", SqlDbType.DateTime).Value = to_DateTimePicker.Value
		cmdupdate.Parameters.Add("@errorDetails", SqlDbType.NVarChar).Value = "%" + txtErrorDetails.Text & "%"
		cmdupdate.Parameters.Add("@IpAddress", SqlDbType.NVarChar).Value = "%" + txtClientIp.Text & "%"
		cmdupdate.Parameters.Add("@responseStatus", SqlDbType.NVarChar).Value = "%" + txtResponseStatus.Text & "%"
		cmdupdate.Parameters.Add("@ticketNo", SqlDbType.NVarChar).Value = "%" + txtTicketNo.Text & "%"
		cmdupdate.Parameters.Add("@editData", SqlDbType.NVarChar).Value = newData '//Data we give

		Dim nChanged = cmdupdate.ExecuteNonQuery()

		If nChanged > 1 Then
			' More than one row was updated. This is probably a Big Problem.
		End If

	End Using

End Sub

Private Sub ShowDataGridView()
	'TODO: write the ShowDataGridView() sub.
End Sub

Private Sub btn_Update_Click(sender As Object, e As EventArgs) Handles btn_Update.Click
	Dim colName = "Some method to select a column would go here."
	Dim newData = txtEditdata.Text

	UpdateDataInColumn(colName, newData)
	ShowDataGridView()

End Sub

huangapple
  • 本文由 发表于 2020年1月6日 21:56:07
  • 转载请务必保留本文链接:https://go.coder-hub.com/59613390.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定