8 Replies - 2272 Views - Last Post: 09 December 2012 - 03:19 PM Rate Topic: -----

#1 oah1837  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 3
  • Joined: 08-December 12

C# mysql example Command.ExecuteReader throws exception

Posted 08 December 2012 - 11:43 PM

I am writing a segment of C# code to get some data from mysql database. I have started with ready-made example but it gave me an error at
 rdr = cmd.ExecuteReader() 


A screen Shot of the thrown exception is shown below as well

using System;
using MySql.Data.MySqlClient; 

public class Program
{

    static void Main() 
    {
            string serverName = "192.168.0.012";
            string port = "1234";
            string db = "cust_db";
            string userID = "root";
            string password = "pass";
            string cs = "Server=" + serverName + ";Port=" + port + ";Database=" + db + ";Uid=" + userID + ";password=" + password;


        MySqlConnection conn = null;
        MySqlDataReader rdr = null;

        try 
        {
            conn = new MySqlConnection(cs);
            conn.Open();

            string stm = "SELECT * FROM cust_tb";
            MySqlCommand cmd = new MySqlCommand(stm, conn);
            rdr = cmd.ExecuteReader();

            while (rdr.Read()) 
            {
                Console.WriteLine(rdr.GetInt32(0) + ": " 
                    + rdr.GetString(1));
            }

        } catch (MySqlException ex) 
        {
            Console.WriteLine("Error: {0}",  ex.ToString());

        } finally 
        {
            if (rdr != null) 
            {
                rdr.Close();
            }

            if (conn != null) 
            {
                conn.Close();
            }

        }
    }
}




the erroe i'm getting:

at MySql.Data.MySqlClient.CharSetMap.GetChararcterSet(DBVersion version, String CharSetName)
at MySql.Data.MySqlClient.NativeDriver.GetFieldMetaData41()
at MySql.Data.MySqlClient.NativeDriver.GetFieldMetaData()
at MySql.Data.MySqlClient.NativeDriver.ReadColumnMetadata(Int32 count)
at MySql.Data.MySqlClient.MySqlDataReader.NextResult()
at MySql.Data.MySqlClient.MySqlCommand.ExecuteReader(Commandbehavior behavior)
at MySql.Data.MySqlClient.MySqlCommand.ExecuteReader()
at Program.Main() in c:\Users\omran.alhammadi\Desktop\csMysqlConnection\csMysqlConnection\Program.cs:line 28
at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Threading.ThreadHelper.ThreadStart()</StackTrace><ExceptionString>System.Collections.Generic.KeyNotFoundException: The given key was not present in the dictionary.
at System.Collections.Generic.Dictionary`2.get_Item(TKey key)
at MySql.Data.MySqlClient.CharSetMap.GetChararcterSet(DBVersion version, String CharSetName)
at MySql.Data.MySqlClient.NativeDriver.GetFieldMetaData41()
at MySql.Data.MySqlClient.NativeDriver.GetFieldMetaData()
at MySql.Data.MySqlClient.NativeDriver.ReadColumnMetadata(Int32 count)
at MySql.Data.MySqlClient.MySqlDataReader.NextResult()
at MySql.Data.MySqlClient.MySqlCommand.ExecuteReader(Commandbehavior behavior)
at MySql.Data.MySqlClient.MySqlCommand.ExecuteReader()
at Program.Main() in c:\Users\omran.alhammadi\Desktop\csMysqlConnection\csMysqlConnection\Program.cs:line 28
at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Threading.ThreadHelper.ThreadStart()</ExceptionString></Exception></TraceRecord>
An unhandled exception of type 'System.Collections.Generic.KeyNotFoundException' occurred in mscorlib.dll
Additional information: The given key was not present in the dictionary.
The program '[17084] csMysqlConnection.vshost.exe: Managed (v4.0.30319)' has exited with code -1 (0xffffffff).

Posted Image

This post has been edited by modi123_1: 09 December 2012 - 11:26 AM
Reason for edit:: fixed image tags


Is This A Good Question/Topic? 0
  • +

Replies To: C# mysql example Command.ExecuteReader throws exception

#2 Momerath  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 994
  • View blog
  • Posts: 2,382
  • Joined: 04-October 09

Re: C# mysql example Command.ExecuteReader throws exception

Posted 09 December 2012 - 01:15 AM

I suspect that the database isn't open (you don't check before you attempt to use it).

MySQL Connector/Net uses 'Pwd', not 'password' for the connection string
Was This Post Helpful? 0
  • +
  • -

#3 oah1837  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 3
  • Joined: 08-December 12

Re: C# mysql example Command.ExecuteReader throws exception

Posted 09 December 2012 - 01:55 AM

View PostMomerath, on 09 December 2012 - 01:15 AM, said:

I suspect that the database isn't open (you don't check before you attempt to use it).

MySQL Connector/Net uses 'Pwd', not 'password' for the connection string


i changed the connection string (Pwd instead of password) and still I am getting the same error
Was This Post Helpful? 0
  • +
  • -

#4 Momerath  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 994
  • View blog
  • Posts: 2,382
  • Joined: 04-October 09

Re: C# mysql example Command.ExecuteReader throws exception

Posted 09 December 2012 - 02:45 AM

Did you check if the connection was open?
Was This Post Helpful? 0
  • +
  • -

#5 oah1837  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 3
  • Joined: 08-December 12

Re: C# mysql example Command.ExecuteReader throws exception

Posted 09 December 2012 - 02:51 AM

View PostMomerath, on 09 December 2012 - 02:45 AM, said:

Did you check if the connection was open?


yes and I could run this query "SELECT VERSION( )" successfully
Was This Post Helpful? 0
  • +
  • -

#6 Momerath  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 994
  • View blog
  • Posts: 2,382
  • Joined: 04-October 09

Re: C# mysql example Command.ExecuteReader throws exception

Posted 09 December 2012 - 04:34 AM

What's the definition of the table? And what character set are you using?

This post has been edited by Momerath: 09 December 2012 - 04:36 AM

Was This Post Helpful? 0
  • +
  • -

#7 tlhIn`toq  Icon User is online

  • Please show what you have already tried when asking a question.
  • member icon

Reputation: 5316
  • View blog
  • Posts: 11,355
  • Joined: 02-June 10

Re: C# mysql example Command.ExecuteReader throws exception

Posted 09 December 2012 - 08:23 AM

Personally I'd recommend not trying to do everything in one long method. That's way we have methods: To break down tasks into small discrete purposes.

Let me get you started with this method from one of my MySQL projects. This is working code from a working project so there is no need to fiddle with it to get it to work. In other words: It ain't broke so don't fix it.

You just need to create three variables for it to use: ServerAddress, UserName, UserPassword.

        public bool OpenConnection()
        {
            bool success = false;
            try
            {
                string connectionString = string.Format("SERVER={0}; UID={1}; Pwd={2}",
                                                        ServerAddress,
                                                        UserName,
                                                        UserPassword);
                    

                if (_connection == null || string.IsNullOrWhiteSpace(_connection.ConnectionString)) _connection = new MySqlConnection(connectionString);
                if (_connection.State == ConnectionState.Open)
                {
                    dbResponse = "Connection already open"; // Bound property to show feedback on the WPF GUI
                    success = true;
                }

                if (!success)
                {
                    _connection.Open();
                    success = _connection.State == ConnectionState.Open;
                    dbResponse = "Connection " + (success ? "Successful" : "Failed");
                }
                return success;
            }
            catch (MySqlException ex)
            {
                switch (ex.Number)
                {
                    case 0:
                        dbResponse = "Cannot connect to server";
                        break;

                    case 1045:
                        dbResponse = "Invalid username/password, please try again";
                        break;
                }
                return false;
            }
        }


Was This Post Helpful? 0
  • +
  • -

#8 JackOfAllTrades  Icon User is offline

  • Saucy!
  • member icon

Reputation: 5951
  • View blog
  • Posts: 23,210
  • Joined: 23-August 08

Re: C# mysql example Command.ExecuteReader throws exception

Posted 09 December 2012 - 03:14 PM

Quote

string serverName = "192.168.0.012";


Are you sure that's a valid IP address?
Was This Post Helpful? 0
  • +
  • -

#9 tlhIn`toq  Icon User is online

  • Please show what you have already tried when asking a question.
  • member icon

Reputation: 5316
  • View blog
  • Posts: 11,355
  • Joined: 02-June 10

Re: C# mysql example Command.ExecuteReader throws exception

Posted 09 December 2012 - 03:19 PM

Its legal. Whether it is correct for the OP is another story. Its a private address that can't be seen outside of being on the same router if that helps the OP make a decision.
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1