gpt4 book ai didi

c# - 输入字符串错误

转载 作者:行者123 更新时间:2023-11-30 20:49:48 25 4
gpt4 key购买 nike

代码如下:

 string checkuser = "select * from [User] where UserName='" + txtusername.Text + "'";
SqlCommand com = new SqlCommand(checkuser, con);
int temp = Convert.ToInt32(com.ExecuteScalar().ToString());
con.Close();
if (temp == 1)

问题:

每当我运行以下代码时,它都会报错,提示输入字符串的格式不正确

最佳答案

试试

string checkuser = "select count(*) from [User] where UserName=@UserName";

你的问题是 ExecuteScalar 返回结果的第一行第一列值,它不能转换为整数

如果您有数字列,例如 age,请执行以下操作

string checkuser = "select age from [User] where UserName=@UserName";

你的sql语句广泛存在sql注入(inject)攻击,你最好使用参数

string sql= "select count(*) from [User] where UserName = @UserName";
using(SqlConnection con = new SqlConnection(conString))
using(SqlCommand cmd= new SqlCommand(sql, con))
{
con.Open();
cmd.Parameters.AddWithValue("@UserName", txtusername.Text);
int temp = Convert.ToInt32(cmd.ExecuteScalar().ToString());
if(temp == 1)
{}
}

关于c# - 输入字符串错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23106348/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com