如何将varchar值转换为数据类型int(在C#中) [英] How do I convert a varchar value to data type int (in C#)

查看:183
本文介绍了如何将varchar值转换为数据类型int(在C#中)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好,

我是团队新手,C#新手,所以下面我有这个代码,我试图将值从gridview传递到数据库...所以,我是收到此消息:将varchar Valor值转换为数据类型int时转换失败

感谢您的帮助,谢谢

Hi all,
I am new in the team and new in C#, so below i have this code, i am trying to pass values from gridview to the database... so, I am getting this message: "Conversion failed when converting the varchar Valor value to data type int"
I appreciate your help, thanks

System.Data.SqlClient.SqlConnection sqlConnection1 = new System.Data.SqlClient.SqlConnection
(@"Data Source=HP\SQLEXPRESS;Initial Catalog=Storebook;User ID=****;Password=********");

            System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand();
            cmd.CommandType = System.Data.CommandType.Text;
            cmd.CommandText = "INSERT INTO Itens (Price) " +
                    "VALUES ('@Num')";
            cmd.Connection = sqlConnection1;

            sqlConnection1.Open();

            for (int i = 0; i < itensDataGridView.Rows.Count; i++)
            {
                cmd.Parameters.Clear();
                int Valor = Convert.ToInt32(itensDataGridView.Rows[i].Cells[1].Value);
                cmd.Parameters.AddWithValue("@Price", Valor);

                cmd.ExecuteNonQuery();
                sqlConnection1.Close();
            }

推荐答案

更正您的查询 -

Correct your query -
cmd.CommandText = "INSERT INTO Itens (Price) " +
"VALUES (@Num)



删除单引号。



作为备注, Itens 可能是错误的表格( Items 也许?)。


Remove the single quotes.

As a note, Itens may be the wrong table(Items maybe?).


问题在于你的sql
cmd.CommandText = "INSERT INTO Itens (Price) " + "VALUES ('@Num')";





将其更改为



Change it to

cmd.CommandText = "INSERT INTO Itens (Price) " +
        "VALUES (@Num)";



我删除了参数周围的单引号,这些引号强制该值为varchar。



参数化查询在添加varchar值时会处理单引号,因此您不需要在基本sql字符串中使用它们


I removed the single quotes surround the parameter which were forcing the value to be a varchar.

Parameterised queries take care of the single quotes when you add varchar values so you don't need them in your base sql string then either


我会没有注意到,谢谢你的帮助。
I would not have noticed, thanks for the help.


这篇关于如何将varchar值转换为数据类型int(在C#中)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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