首页 > 解决方案 > 使用 sql 出现错误“输入字符串的格式不正确”

问题描述

我无法从我的 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:)

我的代码有什么问题?

标签: c#sql-serverssms

解决方案


尝试这个:

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");
}

推荐阅读