SQL 关于在查询中使用参数的 datagridview 撇号的错误

SQL Error Regarding apostrophe from datagridview using parameter in query

Dim sc = datagridview.rows(0).cells(0).value
cmd = New SqlCommand("insert into Schedule (Name) values(@sc)", con)
with cmd
                .Connection = con
                .CommandType = CommandType.Text
                .Parameters.AddWithValue("@sc", sc.cells(0))
end with

datagrid 视图中的值包含一个撇号,在 ('s) 中出现错误。有解决办法吗?

编辑: 这是错误:

SqlException was unhandled. Incorrect syntax near 's'.

编辑 2:我已将代码修改为:

for 1=0 to datagridview.rows.count -1 
Dim tname = datagridview.Rows(i)
cmd = New SqlCommand("insert into Schedule (Name) values(@sc)", con)
with cmd
                 .Connection = con
                 .CommandType = CommandType.Text
                 .Parameters.AddWithValue("@sc", sc.cells(0).value) 
 end with
 con.Close() 
 con.Open()  
 If Not cmd.ExecuteNonQuery() > 0 Then
    con.Close()
    Exit For
 End If
 next

错误还是一样

尝试将“'”替换为“''”



Dim sc = datagridview.rows(0).cells(0).value
cmd = New SqlCommand("insert into Schedule (Name) values(@sc)", con)
with cmd
                .Connection = con
                .CommandType = CommandType.Text
                .Parameters.AddWithValue("@sc", replace(sc.cells(0), "'", "''")
end with

/**** 编辑 ****/ 顺便说一句,我会考虑您的代码在影响价值方面存在问题。您将值输入 SC 然后尝试再次从 cell

中获取值
Dim sc = datagridview.rows(0).cells(0).value
cmd = New SqlCommand("insert into Schedule (Name) values(@sc)", con)
with cmd
                .Connection = con
                .CommandType = CommandType.Text
                .Parameters("@sc").value = sc.replace("'", "''")
end with

由于它一次快速地遍历所有值,我将建立一次连接并为每次迭代更改参数值,如下所示:

Dim sql = "INSERT INTO [Schedule] ([Name]) VALUES(@sc)"

Using conn As New SqlConnection("your connection string"),
       cmd As New SqlCommand(sql, conn)

    cmd.Parameters.Add(New SqlParameter With {.ParameterName = "@sc",
                       .SqlDbType = SqlDbType.NVarChar,
                       .Size = -1})

    conn.Open()

    For i = 0 To dgv.Rows.Count - 1
        Dim tname = dgv.Rows(i).Cells(0).Value.ToString()
        cmd.Parameters("@sc").Value = tname
        cmd.ExecuteNonQuery()
    Next

End Using

在其声明中包含参数的大小有助于SQL服务器保持整洁(查询缓存中只需要一个条目)。

Using 语句确保连接和命令在完成后被正确处理。

我不清楚检查 If Not cmd.ExecuteNonQuery() > 0 的目的,所以我没有把它放进去。 (我使用“dgv”作为 DataGridView 的名称。)