sql-server - 基于文本框的 SQL Server 删除/插入不起作用。- 对比 2010
问题描述
我的 VS 2010 程序有一个 Datagridview,它从 SQL Server 数据库加载数据,现在我添加了几个文本框来添加新行和更新现有行。
这是按钮的子:
Imports System.Configuration
Imports System.Data
Imports System.Data.SqlClient
Imports System.Data.SqlTypes
Imports System.IO
Public Class macmaster
'variables to be used'
Dim myCmd As SqlCommand 'create SQL command'
Dim myReader As SqlDataReader 'pull data'
Dim dt As New DataTable 'store data'
Dim intResult As MsgBoxResult
Dim strSQL As String
Private Sub MacSave_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MacSave.Click
Dim myConn = New SqlConnection("server=server;database=SQL;uid=pro;pwd=abcd") 'form connection'
Try 'alert user if any fields not filled in'
If Me.MacNm.Text.Trim = "" Then
'**this portion of code not relevant**'
Else 'proceed next step if all fields ok.'
intResult = MsgBox("Are you sure to Add/Update?", MsgBoxStyle.OkCancel)
If intResult = MsgBoxResult.Ok Then
'call connection (myConn)'
myConn.Open()
myCmd.CommandText = "DELETE FROM [SQL].[dbo].[Mac] WHERE Machine='" & MacNm.Text & "'"
myCmd.CommandText = "INSERT INTO [SQL].[dbo].[Mac](Machine, PIC, Die) VALUES('" & MacNm.Text & "','" & MacPIC.Text & "','" & MacDie.Text & "')"
MsgBox("Record Added!")
myConn.Close()
End If
End If
Catch ex As Exception
MsgBox(ex.Message, MsgBoxStyle.Critical, "btnAdd_Click Exception")
End Try
End Sub
End Class
在测试期间,我尝试了按钮。代码一直运行,直到我收到消息框说记录已添加。
但是检查 SQL Server 数据库,我发现数据甚至没有改变。两部分 SQL 查询均未触发。我什至还在 SQL Server 上测试了这两个查询。工作正常。是我如何引用有问题的文本框吗?
解决方案
您缺少 ExecuteNonQuery()。
myCmd = New SqlCommand()
myCmd.Connection= myConn
mnyCmd.CommandType= CommandType.Text
Dim commands As String
commands= "DELETE FROM [SQL].[dbo].[Mac] WHERE Machine='" & MacNm.Text & "';"&"INSERT INTO [SQL].[dbo].[Mac](Machine, PIC, Die) VALUES('" & MacNm.Text & "','" & MacPIC.Text & "','" & MacDie.Text & "')"
myCmd.CommandText = commands
myCmd.ExecuteNonQuery()
MsgBox("Record Added!")
推荐阅读
- react-native - 排队离线请求然后同步到服务器(redux-saga)
- elasticsearch - 为什么我在浏览器中看不到 kibana?而不是它,我看到经典错误 404 not found
- python-3.x - 为什么打印元组时出现语法错误?
- java - 如何在AndroidStudio的EditText中填写浮点数和整数
- c - 使用 Webassembly 在 C 中实现 Rust 生成的 API
- ios - UISearchBar 过滤自定义 UITableViewCells
- r - 使用`read.csv`时如何防止分隔符成为输入的一部分?
- typescript - 如何调用方法来运行索引的所有实例
- mysql - Mysql docker 文件未运行:断言失败:log0recv.cc:3561:err == DB_SUCCESS 线程 139674864518912
- arrays - C - 动态分配 3 维数组的函数(使用 malloc)