Reputation: 37
my code is erroring on the line of
mCommand.CommandText = CommandText;
The error is as follows:
An unhandled exception of type 'System.NullReferenceException' occurred in Program.exe
Additional information: Object reference not set to an instance of an object.
If you can help me fix this or link me to a diffrent mysql system with working datarows. I have tried lots of codes and made loads of questions but i cant find any easy working code that works 100% with how i want it to work.
I hope you can help with this problem. All i am trying to do is get the id of the user by their username if you look in the query and to fix the exception of the .CommandText
Full void
public static DataSet ExecuteQuerySet(string CommandText)
{
DataSet DataSet = new DataSet();
mCommand.CommandText = CommandText;
using (MySqlDataAdapter Adapter = new MySqlDataAdapter(mCommand))
{
Adapter.Fill(DataSet);
}
ResetCommand();
return DataSet;
}
Form code -
MySqlConnection Connection = new MySqlConnection(strMySqlConnectionString);
DataRow row = Micro_Talk.MySQL.ExecuteQueryRow("SELECT * FROM users WHERE username = '" + username + "'");
Full mysql class
using MySql.Data.MySqlClient;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Micro_Talk
{
public static class MySQL
{
public static MySqlCommand mCommand;
public static void ResetCommand()
{
mCommand.CommandText = null;
}
public static DataSet ExecuteQuerySet(string CommandText)
{
DataSet DataSet = new DataSet();
mCommand.CommandText = CommandText;
using (MySqlDataAdapter Adapter = new MySqlDataAdapter(mCommand))
{
Adapter.Fill(DataSet);
}
ResetCommand();
return DataSet;
}
public static DataTable ExecuteQueryTable(string CommandText)
{
DataSet DataSet = ExecuteQuerySet(CommandText);
return DataSet.Tables.Count > 0 ? DataSet.Tables[0] : null;
}
public static DataRow ExecuteQueryRow(string CommandText)
{
DataTable DataTable = ExecuteQueryTable(CommandText);
return DataTable.Rows.Count > 0 ? DataTable.Rows[0] : null;
}
}
}
Upvotes: 0
Views: 90
Reputation: 3819
As posted in the comments, you need to properly initialize your mCommand
variable. Try something like this (I modified your query slightly and renamed your connection variable) :
// set up your connection
MySqlConnection myConnection= new MySqlConnection(strMySqlConnectionString);
// format your query
string mySelectQuery = string.Format("SELECT * FROM users WHERE username = '{0}' LIMIT 1", username);
// initalize your command properly
MySqlCommand mCommand = new MySqlCommand(mySelectQuery);
mCommand.CommandType = CommandType.Text;
// set your connection
mCommand.Connection = myConnection;
Since you're only looking for one result here, you can use ExecuteScalar
, as we've established we only want one result back in the query :
// get the result
string result = mCommand.ExecuteScalar().ToString();
Upvotes: 1