转换失败而转换为varchar到int背后
问题描述:
protected void DropDownList3_SelectedIndexChanged(object sender, EventArgs e)
{
string countryid = Convert.ToString(DropDownList3.SelectedValue);
con.Open();
SqlCommand cmd = new SqlCommand("select * from states where countryID=" + countryid, con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
con.Close();
DropDownList4.DataSource = ds;
DropDownList4.DataTextField = "stateName";
DropDownList4.DataValueField = "stateID";
DropDownList4.DataBind();
DropDownList4.Items.Insert(0,new ListItem("--select--","0"));
if (DropDownList4.SelectedValue == "0")
{
DropDownList6.Items.Clear();
DropDownList6.Items.Insert(0, new ListItem("--select--", "0"));
}
表结构:
CREATE TABLE countries
(
countryID varchar(3) NOT NULL,
countryName nvarchar(100) NOT NULL,
localName nvarchar(100),
webCode varchar(2),
region varchar(50),
continent varchar(25),
latitude float NOT NULL,
longitude float NOT NULL,
surfaceArea float NOT NULL,
population int NOT NULL,
PRIMARY KEY (countryID),
UNIQUE (webCode),
UNIQUE (countryName)
);
错误:
System.Data.SqlClient.SqlException: Conversion failed when converting the varchar value 'USA' to data type int.
答
使用这一个:
SqlCommand cmd = new SqlCommand("select * from states where countryID='" + countryid + "'", con);
其实你错过了单引号和你的表CountryID
是varchar
所以你必须使用单引号
小鲍比表警报! –
countryid变龋'美国'值,修复它。 –
[SQL注入警报](http://msdn.microsoft.com/en-us/library/ms161953%28v=sql.105%29.aspx) - 你应该**不**连接你的SQL语句 - 使用**参数化查询**,而不是为了避免SQL注入 - 检查[小Bobby表](https://xkcd.com/327/) –