SQL INSERT语句-VB.net [英] SQL INSERT Statement-VB.net

查看:196
本文介绍了SQL INSERT语句-VB.net的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我找不到此代码中的错误
我试图点击按钮时,我会收到此消息

插入语句中的列多于values子句中指定的值"

NOTE: button1 is ADD button

I can''t find the error in this code
Im receiving this message whenever Im trying to click the button

"there are more columns in the insert statement than values specified in the values clause"

NOTE: button1 is ADD button

Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
        Dim con As New SqlConnection
        Dim cmd As New SqlCommand
 
        Try
            con.ConnectionString = "Data Source=TYNE-PC;Initial Catalog=trial;Integrated Security=True"
            con.Open()
            cmd.Connection = con
    
            cmd = New SqlCommand("insert into records ([emp_id], [emp_name], [pos], [dept_name], [salary], [date]) values ('" & TextBox1.Text & "','" & TextBox2.Text & "','" & TextBox3.Text & "," & TextBox5.Text & "','" & TextBox6.Text & "','" & DateTimePicker1.Value.Date & "')", con)
 
            cmd.ExecuteNonQuery()
 
        Catch ex As Exception
 
            MessageBox.Show("Invalid" & ex.Message)
        Finally
            con.Close()
        End Try
        Me.RecordsTableAdapter.Fill(Me.TrialDataSet1.records)
    End Sub

推荐答案

您错过了一两个报价:
You missed a quote or two:
cmd = New SqlCommand("insert into records ([emp_id], [emp_name], [pos], [dept_name], [salary], [date]) values ('" & TextBox1.Text & "','" & TextBox2.Text & "','" & TextBox3.Text & "," & TextBox5.Text & "','" & TextBox6.Text & "','" & DateTimePicker1.Value.Date & "')", con)


成为


Becomes

cmd = New SqlCommand("insert into records ([emp_id], [emp_name], [pos], [dept_name], [salary], [date]) values ('" & TextBox1.Text & "','" & TextBox2.Text & "','" & TextBox3.Text & "','" & TextBox5.Text & "','" & TextBox6.Text & "','" & DateTimePicker1.Value.Date & "')", con)



但是不要那样做!
不要连接字符串以构建SQL命令.它使您对意外或蓄意的SQL注入攻击敞开大门,这可能会破坏整个数据库.改为使用参数化查询.



But don''t do it like that!
Do not concatenate strings to build a SQL command. It leaves you wide open to accidental or deliberate SQL Injection attack which can destroy your entire database. Use Parametrized queries instead.


TextBox3.Text


后缺少单引号('').




TextBox3.Text & ","


应该是


should be

TextBox3.Text & "'',''"


这篇关于SQL INSERT语句-VB.net的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆