asp.net数据库连接 [英] asp.net database connectivity

查看:82
本文介绍了asp.net数据库连接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请看下面的代码:

please look at the following code:

protected void Button2_Click(object sender, EventArgs e)
    {
        SqlConnection con = new SqlConnection(constring);
        
        SqlCommand cmd = new SqlCommand();
       
        if (DropDownList3.SelectedItem.Text == "Economy")
        {
            seats = Convert.ToInt32(DropDownList1.SelectedItem.Text);

            cmd.Connection = con;
            con.Open();
            cmd.CommandText = "select easeats from flight where fno='" + fn + "'";
           int eds = Convert.ToInt32(cmd.ExecuteScalar());
            
           if (eds > seats)
            {
                Panel2.Visible = true;                //seats available
                cl = DropDownList3.SelectedItem.Text;  
                seat = seats.ToString();
                seats = eds;
            }


我在该行中遇到错误
int eds = Convert.ToInt32(cmd.ExecuteScalar());
如:
将varchar值转换为int数据类型时,转换失败.


i am getting an error in the line
int eds = Convert.ToInt32(cmd.ExecuteScalar());
as:
Conversion failed when converting the varchar value to data type int.

推荐答案

查看fn中的值-它没有转换为整数以与fno进行比较.

顺便说一句:不要那样做.不要连接字符串以构建SQL命令.它使您对意外或蓄意的SQL注入攻击敞开大门,这可能会破坏整个数据库.改为使用参数化查询.
Look at the value in fn - it is not converting to a integer to compare against fno.

BTW: Don''t do it that way. Do not 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.


尝试:
cmd.CommandText = "select easeats from flight where fno=" + fn ;



根据该错误,看起来"fno"是一个int类型的字段,因此传递的值不应用单引号引起来.



Based on the error it looks like ''fno'' is a int type field and so the value passed should not be in single quotes.


cmd.CommandText = "select easeats from flight where fno=''" + fn + "''";
int eds = Convert.ToInt32(cmd.ExecuteScalar());


变量easeats可能已声明为varchar,因此可能是导致错误的原因.


variable easeats might have been declared as varchar so may be the cause for error.


这篇关于asp.net数据库连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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