如何从数据库获取数据,然后将其转换为整数数据类型 [英] How do I get the data from database and then convert it into integer datatype

查看:127
本文介绍了如何从数据库获取数据,然后将其转换为整数数据类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在从数据库获取数据并将其转换为整数数据类型时遇到问题



我尝试过:



string constr =provider = microsoft.jet.oledb.4.0; data source = | datadirectory | Flight.mdb;

OleDbConnection con = new OleDbConnection(constr);

con.Open();

string sql =从AllFlights中选择Economy,其中Flight_name ='+ TextBox6.Text +';

OleDbCommand cmd = new OleDbCommand(sql,con);

OleDbDataAdapter da = new OleDbDataAdapter(cmd);

DataSet ds = new DataSet();

da.Fill(ds);

GridView1.DataSource = ds;

GridView1.DataBind();





Int32 anInteger;

anInteger = Convert.ToInt32(sql);

anInteger = Int32.Parse (sql);







它给了呃ror输入字符串的格式不正确。

解决方案

首先,根据 Convert.ToInt32 Method(String)(System) [ ^ ]和

Int32.Parse方法(字符串)(系统) [ ^ ]

两者都转换指定的数字的字符串表示形式为等效的32位有符号整数。这里的关键词是数字的字符串表示,因此罪魁祸首是 sql 变量。调查一下。

或者,使用 Int32。 TryParse方法(String,Int32)(系统) [ ^ ]。

其次,你应该使用参数化SQL [ ^ ]以防止sql注入。

为了实现可持续的自助未来,您应该学习如何如何在Visual C#中跟踪和调试 [ ^ ]

i have a problem in getting the data from database and convert it into integer datatype

What I have tried:

string constr = "provider= microsoft.jet.oledb.4.0;data source=|datadirectory|Flight.mdb";
OleDbConnection con = new OleDbConnection(constr);
con.Open();
string sql = "select Economy from AllFlights where Flight_name='"+TextBox6.Text+"' ";
OleDbCommand cmd = new OleDbCommand(sql, con);
OleDbDataAdapter da = new OleDbDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
GridView1.DataSource = ds;
GridView1.DataBind();


Int32 anInteger;
anInteger = Convert.ToInt32(sql);
anInteger = Int32.Parse(sql);



it is giving the error "Input string was not in a correct format."

解决方案

Firstly, according to Convert.ToInt32 Method (String) (System)[^] and
Int32.Parse Method (String) (System)[^]
Both convert the specified string representation of a number to an equivalent 32-bit signed integer. The key word here is "string representation of a number", so the culprit is that sql variable. Look into it.
Alternatively, use Int32.TryParse Method (String, Int32) (System)[^].
Secondly, you should use parameterized SQL[^] to prevent sql injection.
For a sustainable self-help future, you should learn how to How to trace and debug in Visual C#[^]


这篇关于如何从数据库获取数据,然后将其转换为整数数据类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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