public class Datebase
{
public string search(string sql_num,int num)
{
MySqlConnection mysql = getMySqlCon();
mysql.Open();
String sqlSearch = "SELECT * FROM tablename where mid =" + sql_num;
MySqlCommand mySqlCommand = getSqlCommand(sqlSearch, mysql);
string result=getResultset(mySqlCommand,num);
mysql.Close();
return result;
}
public MySqlConnection getMySqlCon()
{
String mysqlStr = "Database=mircroblog;Data Source=127.0.0.1;User Id=root;Password=*******;pooling=false;CharSet=utf8;port=3306";
MySqlConnection mysql = new MySqlConnection(mysqlStr);
return mysql;
}
public static MySqlCommand getSqlCommand(String sql, MySqlConnection mysql)
{
MySqlCommand mySqlCommand = new MySqlCommand(sql, mysql);
return mySqlCommand;
}
public string getResultset(MySqlCommand mySqlCommand,int num)
{
MySqlDataReader reader = mySqlCommand.ExecuteReader();
string result="";
try
{
while (reader.Read())
{
if (reader.HasRows)
{
result = reader.GetString(num);
break;
}
}
}
catch (Exception)
{
result = "查询失败了!";
}
finally
{
reader.Close();
}
return result;
}
}
注意事项:
1.这段代码是经过修改过的代码,只可以查询以主码,或者码值唯一的数据项,然后通过num制定具体返回那一项
2.需要注意的是,charset=utf8,如果你的数据库不是这个字符集,在查询的时候会抛出异常,显示不在字典中的错误,这时可以通过修改字符集为utf8来解决问题,mysql代码如下
ALTER TABLE tablename CONVERT TO CHARACTER SET utf8;