如何将整数值插入数据库 [英] how do I insert an integer value to my database

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

问题描述

帮助,我不知道如何将整数值插入我的数据库。



当我试图运行它并在我的datagridview中保存一条新记录时错误并说标准表达式中的数据类型不匹配。



我使用的代码:

help, I don't know how to insert integer values into my database.

when i tried to run it and save a new record in my datagridview there's an error and says "Data type mismatch in criteria expression."

code I used:

Private Sub btnSave_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSave.Click

   Dim sqlinsert As String

   sqlinsert = "INSERT INTO Products (ProductID, Product, UnitPrice,CategoryName, CategoryID)" & " VALUES (@ProductID, @Product, @UnitPrice, @CategoryName, @CategoryID)"
   Dim cmd As New OleDb.OleDbCommand(sqlinsert, con1)

   cmd.Parameters.Add(New OleDbParameter("@ProductID", (txtID.Text)))
   cmd.Parameters.Add(New OleDbParameter("@Product", txtProd.Text))
   cmd.Parameters.Add(New OleDbParameter("@UnitPrice", txtPrice.Text))
   cmd.Parameters.Add(New OleDbParameter("@CategoryName", txtCategory.Text))
   cmd.Parameters.Add(New OleDbParameter("@CategoryID", (txtCatID.Text)))

   con1.Open()
   cmd.ExecuteNonQuery()
   con1.Close()

   ClearTextBox(Me)
   RefreshDGV()
   Me.Close()
   ''...

End Sub

推荐答案

这是因为你将字符串值传递给你的参数。



如果参数应映射到数据库中的varchar值,则传递给它字符串值完全有效。



相反,如果这是一个数字类型或日期时间,那么你必须传递一个相应的类型。没有从字符串到其他类型的隐式转换。



例如,对于ProductID参数:

It's because you are passing string values to your parameters.

If the parameter should map to a varchar value in the database, passing it a string value is perfectly valid.

On the contrary, if this is a numeric type, or a datetime, then you have to pass it a corresponding type. There is no implicit conversion from string to other types.

For example, for the ProductID parameter:
Dim productId As Integer
If (Integer.TryParse(txtID.Text, productId))
   cmd.Parameters.Add(New OleDbParameter("@ProductID", productId))
Else
   Throw New ArgumentException("Entered ProductID is not a valid Integer.")
End If


如果是整数,则可以转换为int值并设置为下面

if it is integer you can convert to int value and set as below
cmd.Parameters.AddWithValue("@ProductID", int.Parse(txtID.Text)) 



参考:http://www.dotnetperls.com/int-parse [ ^ ]


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

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