Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot print exception string because Exception.ToString() failed

Tags:

c#

sql

mysql

I am trying to connect MySql database but when executing the code it gives me this error:

Cannot print exception string because Exception.ToString() failed

using System;

using MySql.Data.MySqlClient;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            string connStr = "server=localhost;user=root;database=people;password=slidan4eg";

            MySqlConnection conn = new MySqlConnection(connStr);

            conn.Open();

            string sql = "SELECT name FROM men WHERE id = 2";

            MySqlCommand command = new MySqlCommand(sql, conn);

            string name = command.ExecuteScalar().ToString();

            Console.WriteLine(name);

            conn.Close();

        }
    }
}

UPD: I was try to debug this and debugger said programm is broken on conn.Open();, I thought it might be important enter image description here

like image 313
Егор Avatar asked Aug 14 '26 19:08

Егор


2 Answers

According to your screenshot you have a System.IO.FileNotFoundException and you are missing the System.Security.Permissions assembly. You can use the NuGet-PaketManager in Visual Studio to install it.

like image 176
Markus Safar Avatar answered Aug 16 '26 10:08

Markus Safar


In case of ExecuteScalar you are going to get:

  1. null if cursor is empty
  2. First field value from the cursor's first record if cursor is not empty.

What's going on:

The problem is in the

string name = command.ExecuteScalar().ToString();

line. If cursor is empty, command.ExecuteScalar() returns null and you have exception thrown on null.ToString(); attempt

Code:

In your case we can exploit Convert.ToString() instead of .ToString() which can deal with null:

static void Main(string[] args) {
  string connStr = "...";

  //DONE: Dispose IDisposable with a help of using
  using (MySqlConnection conn = new MySqlConnection(connStr)) {
    conn.Open();

    //DONE: let sql query be readable
    string sql = 
      @"SELECT name 
          FROM men 
         WHERE id = 2";

    using (MySqlCommand command = new MySqlCommand(sql, conn)) {
      // if cursor is empty we'll get null which we turn into "Not Found"
      string name = Convert.ToString(command.ExecuteScalar()) ?? "Not Found";

      Console.WriteLine(name);
    }
  }
}

Another possibility is null propagation ?. operator. Instead of

string name = command.ExecuteScalar().ToString();

put

string name = command.ExecuteScalar()?.ToString() ?? "Not found";
like image 44
Dmitry Bychenko Avatar answered Aug 16 '26 10:08

Dmitry Bychenko