如何解决将数据类型varchar转换为数字的错误 [英] how to solve error of converting datatype varchar to numeric
本文介绍了如何解决将数据类型varchar转换为数字的错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
(当我尝试运行此代码时,它在da.Fill(dth)附近发出错误,将数据类型varchar转换为数字时出错。
(when i am trying to run this code it is giving an error near da.Fill(dth) that error converting data type varchar to numeric)
public partial class ministatement : Form
{
SqlConnection connect = new SqlConnection(@"data source=ABHINAV-PC\ABHI;integrated security=true;initial catalog=ATM;");
public ministatement()
{
InitializeComponent();
}
private void ministatement_Load(object sender, EventArgs e)
{
connect.Open();
SqlCommand cmd = new SqlCommand("select * from transactions where account_no='" + label4.Text +"'" , connect);
DataTable dth = new DataTable();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dth);
dataGridView1.DataSource = dth;
}
}
}
推荐答案
改为使用参数化查询。
Use Parameterized query instead.
SqlCommand cmd = new SqlCommand("select * from transactions where account_no=@AccountNo" , connect);
cmd.Parameters.Add(new SqlParameter("AccountNo", label4.Text))
您的错误似乎是''的用法。如果您的数据库文件是数字,则应使用不带''的值,如下例所示:
You error seems to be the usage of ' '. If your DB filed is numeric you should use the value without ' ' like in the next example:
SqlCommand cmd = new SqlCommand("select * from transactions where account_no=" + label4.Text, connect);
更好的是从UI元素中获取您的值(在您的情况下为label.Text),然后在SQlCommand中使用它:
Better is to get your value from UI element (in your case label.Text), then use it in the SQlCommand:
SqlCommand cmd = new SqlCommand(string.Format("select * from transactions where account_no={0}", yourValue), connect);
这篇关于如何解决将数据类型varchar转换为数字的错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文