如何获取存储在 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# 新手,因为这已经是我尝试它的第四天了。感谢您的帮助!
最佳答案
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
block 也会为我处理这个问题。如果发生异常,旧代码会使连接挂起。 - .Net 开发人员倾向于相信非常小的方法。更重要的是,这个方法应该是一个类的一部分,该类除了其他简单的公共(public)数据访问方法之外什么都没有,也许还有一些用于抽象类中公共(public)代码的私有(private)辅助方法或属性。
- 这里没有异常处理代码。如果您有属于通用数据库访问类一部分的小方法,则异常处理应该处于较高级别,这样您就可以更好地决定如何继续。
关于c# - 将 C# 变量设置为从数据库中选择,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25560752/