我目前正在用 C# 编写一个 MySQL 类,但我不断收到 Null 错误。
object obj = this.Command.ExecuteScalar();
它说那是空的,但是 this.Command 不是空的。如果 ExecuteScalar() 为空,它只会将 obj 附加为空。我的全班都在这里:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MySql.Data.MySqlClient;
using System.Data;
namespace RushEmu.DB
{
public class DbClient : IDisposable
{
public MySqlConnection Connection
{
get;
set;
}
public MySqlCommand Command
{
get;
set;
}
public DbClient(DbManager Manager)
{
Connection = new MySqlConnection(Manager.ConnectionString);
Command = new MySqlCommand();
Command.Connection = Connection;
}
public void AddParamWithValue(string key, object value)
{
Command.Parameters.AddWithValue(key, value);
}
public void Execute(string qry)
{
Command.CommandText = qry;
Command.ExecuteNonQuery();
Command.CommandText = null;
}
public T Return<T>(string qry)
{
Command.CommandText = qry;
if (typeof(T) == typeof(DataTable))
{
DataTable data = new DataTable();
new MySqlDataAdapter(Command).Fill(data);
Command.CommandText = null;
return (T)(object)data;
}
else if (typeof(T) == typeof(DataRow))
{
DataTable data = new DataTable();
new MySqlDataAdapter(Command).Fill(data);
Command.CommandText = null;
if (data.Rows.Count > 0)
{
return (T)(object)data.Rows[0];
}
else
{
return default(T);
}
}
else if (typeof(T) == typeof(MySqlDataReader))
{
MySqlDataReader reader = Command.ExecuteReader();
Command.CommandText = null;
return (T)(object)reader;
}
else if (typeof(T) == typeof(int))
{
int i = Convert.ToInt32(Command.ExecuteScalar());
Command.CommandText = null;
return (T)(object)i;
}
else if (typeof(T) == typeof(uint))
{
uint i = Convert.ToUInt32(Command.ExecuteScalar());
Command.CommandText = null;
return (T)(object)i;
}
else if (typeof(T) == typeof(string))
{
object obj = this.Command.ExecuteScalar();
string i = (string)obj;
Command.CommandText = null;
return (T)(object)i;
}
else if (typeof(T) == typeof(bool))
{
bool i = Convert.ToBoolean(Command.ExecuteScalar());
Command.CommandText = null;
return (T)(object)i;
}
else if (typeof(T) == typeof(DateTime))
{
DateTime i = Convert.ToDateTime(Command.ExecuteScalar());
Command.CommandText = null;
return (T)(object)i;
}
else
{
return default(T);
}
}
void IDisposable.Dispose()
{
}
}
}