将varchar值'hello'转换为数据类型int时转换失败。 [英] Conversion failed when converting the varchar value 'hello ' to data type int.

查看:108
本文介绍了将varchar值'hello'转换为数据类型int时转换失败。的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

System.Data.dll中发生了'System.Data.SqlClient.SqlException'类型的未处理异常



附加信息:转换varchar值时转换失败'hello'到数据类型int。



我尝试过:



 使用系统; 
使用 System.Collections.Generic;
使用 System.ComponentModel;
使用 System.Data;
使用 System.Drawing;
使用 System.Linq;
使用 System.Text;
使用 System.Threading.Tasks;
使用 System.Windows.Forms;
使用 System.Data.SqlClient;

命名空间 Invoice_Genraton
{
public partial class Form1:Form
{
public Form1()
{
InitializeComponent();
}

private void Form1_Load( object sender,EventArgs e)
{

}

private void textBox1_TextChanged( object sender,EventArgs e)
{

}
SqlDataAdapter da;
DataSet ds;
SqlConnection con;
private void btnSubmit_Click( object sender,EventArgs e)
{
con = new SqlConnection( < span class =code-string> Data Source = localhost; Initial Catalog = allcare; Integrated Security = True; Pooling = False);
da = new SqlDataAdapter( insert into [prudhvi] values(' + textBox1.Text + ',' + textBox2.Text + ',' + textBox3.Text + ','
+ textBox4.Text + < span class =code-string>',' + textBox5.Text + ',' + textBox6.Text + ',' + textBox7.Text + ',' + textBox8.Text + ',' +
textBox9.Text + ',' + textBox10.Text + ',' + ') ,con);
ds = new DataSet();
da.Fill(ds);
Form2 f2 = new Form2();
this .Hide();
f2.label12.Text = textBox1.Text.ToString();
f2.label13.Text = textBox2.Text.ToString();
f2.label14.Text = textBox3.Text.ToString();
f2.label15.Text = textBox4.Text.ToString();
f2.label16.Text = textBox5.Text.ToString();
f2.label17.Text = textBox6.Text.ToString();
f2.label18.Text = textBox7.Text.ToString();
f2.label19.Text = textBox8.Text.ToString();
f2.label20.Text = textBox9.Text.ToString();
f2.label21.Text = textBox10.Text.ToString();

int n1 = int .Parse(textBox9.Text);
int n2 = int .Parse(textBox10.Text);
int total = n1 + n2;
f2.label22.Text = total.ToString();
f2.Show();


}
}
}

解决方案

不要这样做!

永远不要连接字符串来构建SQL命令。它让您对意外或故意的SQL注入攻击持开放态度,这可能会破坏您的整个数据库。请改用参数化查询。

当您将其转换为参数化查询时,您将验证并转换C#代码中的所有值,并在错误输入时将错误消息传递给用户 - 然后传递验证和转换后的值直接到SQL:

  int  iVal; 
if (!int.TryParse(txtThisShouldBeANumber.Text, out iVal))
{
...向用户报告输入问题...
return ;
}
使用(da = new SqlDataAdapter( INSERT INTO MyTable(MyColumnName)VALUES(@NUM),com))
{
da。 InsertCommand.Parameters.AddWithValue( @ NUM,iVal);
...
}

对您的用户来说,它更友好,更易于阅读,更易于维护,并且更安全,可以将您的数据库控制权传递给用户!而另一个优势是,你的问题会在同一时间消失......



BTW:帮自己一个忙,并停止使用Visual Studio默认名称 - 你可能还记得今天的TextBox8是手机号码,但是当你必须在三周内修改它时,你会这样吗?使用描述性名称 - 例如tbMobileNo - 您的代码变得更容易阅读,更自我记录,更易于维护 - 并且编码速度更快,因为Intellisense可以通过三次击键来tbMobile,其中TextBox8需要思考大约和8次击键...


永远不要通过连接用户输入来构建SQL查询,它被命名为SQL注入,它对您的数据库很危险并且容易出错。

名称中的单引号和程序崩溃。如果像Brian O'Conner这样的用户输入可能会使您的应用程序崩溃,那么这是一个SQL注入漏洞。

SQL注入 - 维基百科 [ ^ ]

SQL注入 [ ^ ]


实际上你的例外是回答你的问题。





您正在尝试将varchar值插入数据库的int字段



要么你应该将列的数据类型更改为varchar,或者只能将int值插入该特定列



为了更好的实践,还要在Insert语句中写入列名称各自的值

例如



  INSERT   INTO  TABLE_NAME(COLUMN1,COLUMN2 ...) VALUES  @ VAL1  @ VAL2 





如果您对此有任何疑问或疑虑,请与我们联系。


An unhandled exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll

Additional information: Conversion failed when converting the varchar value 'hello ' to data type int.

What I have tried:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;

namespace Invoice_Genraton
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {

        }

        private void textBox1_TextChanged(object sender, EventArgs e)
        {

        }
        SqlDataAdapter da;
         DataSet ds;
         SqlConnection con;
        private void btnSubmit_Click(object sender, EventArgs e)
        {
            con = new SqlConnection("Data Source=localhost;Initial Catalog=allcare;Integrated Security=True;Pooling=False");
            da = new SqlDataAdapter("insert into [prudhvi] values('" + textBox1.Text + "','" + textBox2.Text + "','" + textBox3.Text + "','"
                                        + textBox4.Text + "','" + textBox5.Text + "','" + textBox6.Text + "','" + textBox7.Text + "','" + textBox8.Text + "','" +
                                        textBox9.Text + "','" + textBox10.Text + "','" +  "')", con);
            ds = new DataSet();
            da.Fill(ds);
            Form2 f2 = new Form2();
            this.Hide();
            f2.label12.Text = textBox1.Text.ToString();
            f2.label13.Text = textBox2.Text.ToString();
            f2.label14.Text = textBox3.Text.ToString();
            f2.label15.Text = textBox4.Text.ToString();
            f2.label16.Text = textBox5.Text.ToString();
            f2.label17.Text = textBox6.Text.ToString();
            f2.label18.Text = textBox7.Text.ToString();
            f2.label19.Text = textBox8.Text.ToString();
            f2.label20.Text = textBox9.Text.ToString();
            f2.label21.Text = textBox10.Text.ToString();
            
            int n1 = int.Parse(textBox9.Text);
            int n2 = int.Parse(textBox10.Text);
            int total = n1 + n2;
            f2.label22.Text = total.ToString();
            f2.Show();


        }
    }
}

解决方案

Don't do it like that!
Never 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.
When you convert that to parameterized queries, you validate and convert all your values in your C# code, and pass error messages back to your user when they have mistyped - you then pass the validated and converted values directly to SQL:

int iVal;
if (!int.TryParse(txtThisShouldBeANumber.Text, out iVal))
   {
   ... Report input problem to user ...
   return;
   }
using (da = new SqlDataAdapter("INSERT INTO MyTable (MyColumnName) VALUES (@NUM)", com))
   {
   da.InsertCommand.Parameters.AddWithValue("@NUM", iVal);
   ...
   }

It's more friendly for your users, easier to read, easier to maintain, and a damn site safer that passing control of your DB to the user! And as another advantage, your problem will disappear at the same time...

BTW: Do yourself a favour, and stop using Visual Studio default names for everything - you may remember that "TextBox8" is the mobile number today, but when you have to modify it in three weeks time, will you then? Use descriptive names - "tbMobileNo" for example - and your code becomes easier to read, more self documenting, easier to maintain - and surprisingly quicker to code because Intellisense can get to to "tbMobile" in three keystrokes, where "TextBox8" takes thinking about and 8 keystrokes...


Never build an SQL query by concatenating with user inputs, it is named "SQL injection", it is dangerous for your database and error prone.
A single quote in a name and your program crash. If a user input like "Brian O'Conner" can crash your app, it is an SQL injection vulnerability.
SQL injection - Wikipedia[^]
SQL Injection[^]


Actually your exception is giving an answer of your question.


You are trying to insert varchar value to int field of a database

Either you should alter datatype of a column to varchar or you can insert int values only to that particular column

For better practice write column names also in Insert statement respective of values
e.g.

INSERT INTO TABLE_NAME (COLUMN1,COLUMN2...) VALUES (@VAL1,@VAL2)



Let me know if you have any query or concern for same.


这篇关于将varchar值'hello'转换为数据类型int时转换失败。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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