如何将数据从datagridview插入数据库 [英] How to insert data from datagridview into database

查看:149
本文介绍了如何将数据从datagridview插入数据库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Private Sub insert_Click()

   For each rw as DatagridviewRow in Datagridview1. Rows

      Try
          sql = "insert into Student (ID,name)" &_
          "Values ('" & rw.Cells (0).Value & '",'" & rw.Cells(1).Value &"')"

          conn()
          cmd = New OleDbCommand (sql,conn)
          cmd.ExecuteNonQuery()

      Catch ex As Exception 
          MsgBox (ex.Message)
      End Try
   Next

End Sub.



这是我的代码,b当我尝试插入时,它会在INSERT INTO语句中显示语法错误。



请帮帮我。


That is my code, but when I try to insert, it displays "syntax error in the INSERT INTO statement ".

Please help me.

推荐答案

首先,你应该使用参数化查询 [ ^ ]

它不仅有助于保护您免受SQL注入攻击,还可以省去围绕值的单引号,也不需要转换 .Value .ToString()



如果您注意到格式化的代码,则表明您的引号和双引号出现问题。如果您调试代码并查看变量 sql 的内容,您将看到它无效sql

Firstly, you should use Parameterized queries[^]
Not only does it help to protect you against SQL Injection attacks it also removes the need to worry about those single quotes around values, nor do you need to convert the .Value with .ToString()

If you note your formatted code you appear to have a problem with quotes and double quotes. If you debug your code and look at the contents of the variable sql you will see it is not valid sql
insert into Student (ID, name)Values ('theValue



设置你的sql类似于


Set your sql to be something like

sql = "insert into Student (ID, name) Values (@value1, @value2)"

并为您的命令创建两个参数

and create two parameters for your command

cmd.Parameters.Add(new OleDbParameter("@value1", rw.Cells(0).Value))
cmd.Parameters.Add(new OleDbParameter("@value2", rw.Cells(1).Value))



如果你不确定如何调试你的代码有一个阅读本文 - 掌握Visual Studio 2010中的调试 - 初学者指南 [ ^ ]


这里的单引号配对:

pairing of single quotes here:
rw.Cells (0).Value & '",'" 



应该是


should be

rw.Cells (0).Value & "','" 


这篇关于如何将数据从datagridview插入数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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