0

我的 add 语句工作得很好,但是当它转向编辑数据时它就不起作用了。我一直在想我应该使用什么正确的代码。我真的需要你们的帮助!

我的 add 语句工作得很好,但是当它转向编辑数据时它就不起作用了。我一直在想我应该使用什么正确的代码。我真的需要你们的帮助!

Imports System.Data.SqlClient
Public Class Form1
Dim connetionString As String
Dim cnn As SqlConnection
Dim cmd As SqlCommand
Dim da As SqlDataAdapter
Dim dt As DataTable
Dim ds As DataSet
Dim sql As String
Private Sub btnAdd_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnAdd.Click

            connetionString = "Data Source=xxx;Initial Catalog=xxx;User ID=xxx;Password=xxx"
    sql = "INSERT INTO Table_Info (ID,Name) VALUES ('" & Me.txtID.Text & "','" & Me.txtName.Text & "')"

    cnn = New SqlConnection(connetionString)

    cnn.Open()
    cmd = New SqlCommand(sql, cnn)
    cmd.ExecuteNonQuery()
    cmd.Dispose()
    cnn.Close()

End Sub
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
    'TODO: This line of code loads data into the 'TestDataSet.Table_Info' table. You can move, or remove it, as needed.
    Me.Table_InfoTableAdapter.Fill(Me.TestDataSet.Table_Info)

End Sub
 Private Sub btnEdit_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnEdit.Click

    Dim connetionString As String
    connetionString = "Data Source=xxx;Initial Catalog=xxx;User ID=xxx;Password=xxx"

    cnn = New SqlConnection(connetionString)
    sql = "insert into Table_Info (ID,Name) values('" & txtID.Text & "','" & txtName.Text & "')"
    Try
        cnn.Open()
        da.InsertCommand = New SqlCommand(sql, cnn)
        da.InsertCommand.ExecuteNonQuery()
        MsgBox("err.discription")
    Catch ex As Exception
        MsgBox(ex.ToString)
    End Try



End Sub

结束类

4

1 回答 1

0

几点。

首先,INSERTSQL 命令用于向数据库表中插入新行。如果要编辑现有行,则需要使用该UPDATE命令。它看起来像UPDATE Table_Info SET Name = @name WHERE ID = @id.

其次,你真的不应该构建这样的 SQL 命令字符串。当您将未经验证的用户输入直接传递到数据库中时,您基本上是在向 SQL 注入攻击敞开心扉。您应该看看参数化查询

于 2013-03-08T09:15:12.127 回答