【问题标题】:Error "Input string was not in a correct format" with sql使用 sql 出现错误“输入字符串的格式不正确”
【发布时间】:2019-11-30 04:55:41
【问题描述】:

我无法从我的 sql 数据库中获取 int 值:

if(Convert.ToDouble(dbh.getInfo("firstTime", username))==1)

我也试过了:

if((int)dbh.getInfo("firstTime", username)==1)

这是 getInfo 函数:

public object getInfo(string infoReq, string username)
        {
            string query = "select (@infoReq) from AccountDB where username like @username";
            try
            {
                using (SqlConnection con = new SqlConnection(connectionString))
                {
                    SqlCommand cmd = new SqlCommand(query, con);
                    cmd.Parameters.AddWithValue("@infoReq", infoReq);
                    cmd.Parameters.AddWithValue("@username", username);
                    con.Open();
                    return cmd.ExecuteScalar();
                }
            }
            catch (Exception e){

            }
            return MessageBox.Show("Please check your fields");
        }

dbh 是一个 DBHandler 类型,当然这是该函数的来源

在sql数据库中,这件事@infoReq的DataType有点(在sql中:[firstTime] BIT NOT NULL

我的代码有什么问题?

【问题讨论】:

  • 你调试过你的代码吗? getInfo 方法返回的确切值是多少?你看到消息框Please check your fields 了吗? Select语句中的列不能使用参数。
  • 我不确定您的查询是否有意义。您将 @infoReq 作为字符串传递,然后只返回它,然后尝试将其转换为标量?

标签: c# sql-server ssms


【解决方案1】:

试试这个:

public object getInfo(string infoReq, string username)
{
    string query = "select @infoReq from AccountDB where username like '%@username%'";
    try
    {
        using (SqlConnection con = new SqlConnection(connectionString))
        {
            SqlCommand cmd = new SqlCommand(query, con);
            cmd.Parameters.AddWithValue("@infoReq", infoReq);
            cmd.Parameters.AddWithValue("@username", username);
            con.Open();
            return cmd.ExecuteScalar();
        }
    }
    catch (Exception e){

    }
    return MessageBox.Show("Please check your fields");
}

【讨论】:

  • 您能简单地向我解释一下% 的用途吗?它奏效了
  • % 是 sql 通配符
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-02-08
  • 1970-01-01
  • 1970-01-01
  • 2018-01-01
  • 1970-01-01
相关资源
最近更新 更多