c#ExecuteScalar()返回值的问题
C# code
MySql.Data.MySqlClient.MySqlConnection con = new MySql.Data.MySqlClient.MySqlConnection("Database=gkphpcms;Data Source=localhost;User Id=root;Password=root");
con.Open();
MySql.Data.MySqlClient.MySqlCommand cmd = new MySql.Data.MySqlClient.MySqlCommand("select count(contentid) from phpcms_c_news where contentid="+id, con);
int count = 0;
count = Convert.ToInt32(cmd.ExecuteScalar());//[color=#FF0000]Sql语句查询出来的是0,但是转换过后就变成1了[/color]
if (count == 0)
{
MySql.Data.MySqlClient.MySqlCommand cmdsetgbk = new MySql.Data.MySqlClient.MySqlCommand("set names 'utf8'", con);
cmdsetgbk.ExecuteNonQuery();
MySql.Data.MySqlClient.MySqlCommand cmdinsert = new MySql.Data.MySqlClient.MySqlCommand(@"insert into phpcms_c_news(contentid,template,content,DocUrl,DownType) values(" + id + ",'" + content + "','" + downurls + "','" + classtype + "')", con);
cmdinsert.ExecuteNonQuery();
}
con.Close();
在if(count==0)这一行中,count本来该是0,怎么变成1了。是cmd.ExecuteScalar()的问题,还是转换的问题?
------解决方案--------------------不应该这样的。
object o = cmd.ExecuteScalar();
cmd.Dispose();
if(o == null || (string)o == "")
{
//....
}
这样看看
------解决方案--------------------不可能,
using (SqlConnection conn = new SqlConnection(connString))
{
if (conn.State != ConnectionState.Open)
{
conn.Open();
}
SqlCommand cmd = new SqlCommand();
cmd.Connection = conn;
cmd.CommandText = "select count(*) from category";
cmd.CommandType = CommandType.Text;
object val = cmd.ExecuteScalar();
cmd.Parameters.Clear();
Response.Write(Convert.ToInt32(val));
}
显示结果为0
------解决方案--------------------呵呵,mysql命令行查下?查询下你的查询结果返回多少?如果返回大于0说明查到了相关数据,你要仔细查看你的数据了……
------解决方案--------------------count = int.Parse(cmd.ExecuteScalar());//
------解决方案--------------------这句count = int.Parse(cmd.ExecuteScalar().ToString());//
------解决方案--------------------写不写Convert.ToInt32()都可以返回值吧,初学中。。
------解决方案--------------------1.count = int.Parse(cmd.ExecuteScalar());
2.Convert.ToInt32(cmd.ExecuteScalar());
------解决方案--------------------select count(contentid) from phpcms_c_news where contentid="+id
直接到MYSQL里面执行看看结果是否是1