如何获取存储在Select方法中的信息并将其传输到字符串?我试图从match_id列获取最大值,并将其值从command.CommandText获取到matchCode字符串中。我从哪里开始?
string connectString = "Server=myServer;Database=myDB;Uid=myUser;Pwd=myPass;";
string matchCode = "";
MySqlConnection connect = new MySqlConnection(connectString);
MySqlCommand command = connect.CreateCommand();
command.CommandText = "SELECT MAX(VAL(match_id)) FROM `data`";
try
{
connect.Open();
command.ExecuteNonQuery();
matchCode = "??";
connect.Close();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
我是C#的新手,因为它就像我第四天尝试一样。谢谢你的帮助!
答案 0 :(得分:2)
ExecuteNonQuery()
方法用于INSERT / UPDATE / DELETE查询。如果您只是返回一个值,请使用ExecuteScalar()
。如果您要获得整个结果集,请使用ExecuteReader()
或Fill()
DataSet对象。
此外,您应该做的一些事情是C#的惯用语:
public int GetMatchCode()
{
//this could be loaded from config file or other source
string connectString = "Server=myServer;Database=myDB;Uid=myUser;Pwd=myPass;";
string sql = "SELECT MAX(VAL(match_id)) FROM `data`";
using (var connect = new MySqlConnection(connectString))
using (var command = new MySqlCommand(sql, connect))
{
connect.Open();
var result = command.ExecuteScalar();
if (result == DBNull.Value)
{
//what you do here depends on your application
// if it's impossible for the query to return NULL, you can even skip this
}
return (int)result;
}
}
有些变化需要解释:
.Close()
。即使抛出异常,using
块也会为我处理。如果发生异常,旧代码会挂起连接。