gpt4 book ai didi

c# - SQL从nVarchar到int的转换报错

转载 作者:太空宇宙 更新时间:2023-11-03 13:31:40 27 4
gpt4 key购买 nike

错误:

Conversion failed when converting the nvarchar value 'select TopicID from Topic where TopicName='Data Structure'' to data type int

代码:

public void  BindGridview()
{
string strConnString = ConfigurationManager.ConnectionStrings["infoConnectionString"].ConnectionString;

SqlConnection sqlcon = new SqlConnection(strConnString);
sqlcon.Open();

string strquery2 = "select TopicID from Topic where TopicName='" + ddltopic.SelectedItem.Text+ "'";

string strquery3 = "select i.name ,i.score from info as i,Topic as t where i.topic_id=@topicid";
SqlCommand cmd = new SqlCommand(strquery3,sqlcon);
cmd.Parameters.AddWithValue("@topicid",strquery2);

cmd.Connection = sqlcon;

SqlDataReader dr;;

this.GridView1.DataSource =cmd.ExecuteReader();
this.GridView1.DataBind();

sqlcon.Close();
}
}

谁能告诉我哪里错了?任何帮助将不胜感激..请尽快回复..提前致谢..

最佳答案

您传递的是整个查询中的而不是此处这一行中的主题 id

cmd.Parameters.AddWithValue("@topicid",strquery2);

然后将其作为参数并将其添加到以下查询中。如果这是一个子查询,你总是可以先执行它,然后在参数中使用结果。

但它失败的原因是因为您实际上是在尝试通过传入查询字符串来比较 Stringint

关于c# - SQL从nVarchar到int的转换报错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20278791/

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