SharpDevelop Community

Get your problems solved!
Welcome to SharpDevelop Community Sign in | Join | Help
in Search

trying to connect to MYSQL DB

Last post 05-15-2011 10:21 AM by MattWard. 2 replies.
Page 1 of 1 (3 items)
Sort Posts: Previous Next
  • 05-13-2011 11:40 AM

    • dglnz
    • Not Ranked
    • Joined on 03-05-2011
    • Posts 4

    trying to connect to MYSQL DB

    Following a tutorial fromhttp://gamblis.com/2009/08/07/show-mysql-table-list-in-sharpdevelop/#more-2187

    here is the code i have below (I suspect i've not properly included the Mysql.data .net bits But i have selected them from the Project->AddReference menu options as per the tutorial).

    I Really do suspect i'm missing something here.

     

    Hope some one can help me as I'm trying to understand how to connect to a MYSQL server.

    require "mscorlib"
    require "System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"
    require "System.Drawing, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"

    class MainForm < System::Windows::Forms::Form
        def initialize()
            self.InitializeComponent()
        end

        def InitializeComponent()
            @button1 = System::Windows::Forms::Button.new()
            @listBox1 = System::Windows::Forms::ListBox.new()
            self.SuspendLayout()
            #
            # button1
            #
            @button1.Location = System::Drawing::Point.new(235, 271)
            @button1.Name = "button1"
            @button1.Size = System::Drawing::Size.new(167, 72)
            @button1.TabIndex = 0
            @button1.Text = "button1"
            @button1.UseVisualStyleBackColor = true
            @button1.Click { |sender, e| self.Button1Click(sender, e) }
            #
            # listBox1
            #
            @listBox1.FormattingEnabled = true
            @listBox1.Location = System::Drawing::Point.new(48, 43)
            @listBox1.Name = "listBox1"
            @listBox1.Size = System::Drawing::Size.new(501, 95)
            @listBox1.TabIndex = 1
            #
            # MainForm
            #
            self.ClientSize = System::Drawing::Size.new(610, 400)
            self.Controls.Add(@listBox1)
            self.Controls.Add(@button1)
            self.Name = "MainForm"
            self.Text = "mysql_test"
            self.ResumeLayout(false)
        end
       


        def Button1Click(sender, e)
       
            #Initiate the connection
            #Call the MySQL_mod module
            Try
                MySQL_mod.startconnect
                #After connection is open execute the command to show table list
                Dim SQL As String = "SHOW TABLES;"
                MySQL_mod.command=New MySql.Data.MySqlClient.MySqlCommand(SQL,MySQL_mod.con)
                MySQL_mod.reader = MySQL_mod.command.ExecuteReader
                #Clear the ListBox item
                ListBox1.Items.Clear
                Do While MySQL_mod.reader.Read
                    ListBox1.Items.Add(MySQL_mod.reader.Item(0))
                Loop
                MySQL_mod.reader.Dispose
                #Close the connection after all
                MySQL_mod.con.Close
            Catch ex As Exception
                MsgBox(ex.Message)
            End Try
       
        end
    end

    # code below was in a file on it's own - should it be? this got from the URL above.


    Public con As MySql.Data.MySqlClient.MySqlConnection
    Public command As MySql.Data.MySqlClient.MySqlCommand
    Public adapter As MySql.Data.MySqlClient.MySqlDataAdapter
    Public reader As MySql.Data.MySqlClient.MySqlDataReader

    Public Sub startconnect
            Try
            con=New MySQL.Data.MySqlClient.MySqlConnection
            con.ConnectionString="server=YourMySQLServerhost;user=root;password=t;database=test"
            data = conn.test
            con.Close
            con.Open
            Catch ex As Exception
            puts ex.Message
            puts data
            MsgBox(ex.Message)
            End Try
    End Sub

     

    below is the msg i get....

     

    See the end of this message for details on invoking
    just-in-time (JIT) debugging instead of this dialog box.

    ************** Exception Text **************
    System.MemberAccessException: uninitialized constant MainForm::Try
       at IronRuby.Runtime.RubyContext.ResolveMissingConstant(RubyModule owner, String name)
       at IronRuby.Builtins.ModuleOps.ConstantMissing(RubyModule self, String name)
       at Microsoft.Scripting.Interpreter.FuncCallInstruction`3.Run(InterpretedFrame frame)
       at Microsoft.Scripting.Interpreter.Interpreter.Run(InterpretedFrame frame)
       at Microsoft.Scripting.Interpreter.LightLambda.Run3[T0,T1,T2,TRet](T0 arg0, T1 arg1, T2 arg2)
       at IronRuby.Runtime.RubyContext.Send(CallSite`1& site, String eventName, Object target, String memberName)
       at IronRuby.Builtins.RubyModule.ConstantMissing(String name)
       at IronRuby.Runtime.RubyOps.GetMissingConstant(RubyScope scope, ConstantSiteCache cache, String name)
       at Microsoft.Scripting.Interpreter.FuncCallInstruction`4.Run(InterpretedFrame frame)
       at Microsoft.Scripting.Interpreter.Interpreter.Run(InterpretedFrame frame)
       at Microsoft.Scripting.Interpreter.LightLambda.Run4[T0,T1,T2,T3,TRet](T0 arg0, T1 arg1, T2 arg2, T3 arg3)
       at IronRuby.Runtime.Calls.RubyObjectMethodDispatcherWithScope`2.Invoke[TScope](CallSite callSite, TScope scope, Object self, T0 arg0, T1 arg1)
       at Microsoft.Scripting.Interpreter.DynamicInstruction`5.Run(InterpretedFrame frame)
       at Microsoft.Scripting.Interpreter.Interpreter.Run(InterpretedFrame frame)
       at Microsoft.Scripting.Interpreter.LightLambda.Run4[T0,T1,T2,T3,TRet](T0 arg0, T1 arg1, T2 arg2, T3 arg3)
       at IronRuby.Runtime.Calls.BlockDispatcher2.Invoke(BlockParam param, Object self, Proc procArg, Object arg1, Object arg2)
       at IronRuby.Runtime.RubyOps.Yield2(Object arg1, Object arg2, Proc procArg, Object self, BlockParam blockParam)
       at CallSite.Target(Closure , CallSite , Object , Object , EventArgs )
       at _Scripting_(Object[ , Object , EventArgs )
       at System.Windows.Forms.Control.OnClick(EventArgs e)
       at System.Windows.Forms.Button.OnClick(EventArgs e)
       at System.Windows.Forms.Button.OnMouseUp(MouseEventArgs mevent)
       at System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons button, Int32 clicks)
       at System.Windows.Forms.Control.WndProc(Message& m)
       at System.Windows.Forms.ButtonBase.WndProc(Message& m)
       at System.Windows.Forms.Button.WndProc(Message& m)
       at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
       at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
       at System.Windows.Forms.NativeWindow.Callback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)


    ************** Loaded Assemblies **************
    mscorlib
        Assembly Version: 4.0.0.0
        Win32 Version: 4.0.30319.225 (RTMGDR.030319-2200)
        CodeBase: file:///c:/WINDOWS/Microsoft.NET/Framework/v4.0.30319/mscorlib.dll
    ----------------------------------------
    ir
        Assembly Version: 1.1.3.0
        Win32 Version: 1.1.3.0
        CodeBase: file:///C:/Program%20Files/IronRuby%201.1/bin/ir.exe
    ----------------------------------------
    IronRuby
        Assembly Version: 1.1.3.0
        Win32 Version: 1.1.3.0
        CodeBase: file:///C:/WINDOWS/Microsoft.Net/assembly/GAC_MSIL/IronRuby/v4.0_1.1.3.0__7f709c5b713576e1/IronRuby.dll
    ----------------------------------------
    System.Core
        Assembly Version: 4.0.0.0
        Win32 Version: 4.0.30319.1 built by: RTMRel
        CodeBase: file:///C:/WINDOWS/Microsoft.Net/assembly/GAC_MSIL/System.Core/v4.0_4.0.0.0__b77a5c561934e089/System.Core.dll
    ----------------------------------------
    System
        Assembly Version: 4.0.0.0
        Win32 Version: 4.0.30319.1 built by: RTMRel
        CodeBase: file:///C:/WINDOWS/Microsoft.Net/assembly/GAC_MSIL/System/v4.0_4.0.0.0__b77a5c561934e089/System.dll
    ----------------------------------------
    Microsoft.Dynamic
        Assembly Version: 1.1.0.20
        Win32 Version: 1.1.0.20
        CodeBase: file:///C:/WINDOWS/Microsoft.Net/assembly/GAC_MSIL/Microsoft.Dynamic/v4.0_1.1.0.20__7f709c5b713576e1/Microsoft.Dynamic.dll
    ----------------------------------------
    Microsoft.Scripting
        Assembly Version: 1.1.0.20
        Win32 Version: 1.1.0.20
        CodeBase: file:///C:/WINDOWS/Microsoft.Net/assembly/GAC_MSIL/Microsoft.Scripting/v4.0_1.1.0.20__7f709c5b713576e1/Microsoft.Scripting.dll
    ----------------------------------------
    System.Configuration
        Assembly Version: 4.0.0.0
        Win32 Version: 4.0.30319.1 (RTMRel.030319-0100)
        CodeBase: file:///C:/WINDOWS/Microsoft.Net/assembly/GAC_MSIL/System.Configuration/v4.0_4.0.0.0__b03f5f7f11d50a3a/System.Configuration.dll
    ----------------------------------------
    System.Xml
        Assembly Version: 4.0.0.0
        Win32 Version: 4.0.30319.1 built by: RTMRel
        CodeBase: file:///C:/WINDOWS/Microsoft.Net/assembly/GAC_MSIL/System.Xml/v4.0_4.0.0.0__b77a5c561934e089/System.Xml.dll
    ----------------------------------------
    IronRuby.Libraries
        Assembly Version: 1.1.3.0
        Win32 Version: 1.1.3.0
        CodeBase: file:///C:/WINDOWS/Microsoft.Net/assembly/GAC_MSIL/IronRuby.Libraries/v4.0_1.1.3.0__7f709c5b713576e1/IronRuby.Libraries.dll
    ----------------------------------------
    System.Numerics
        Assembly Version: 4.0.0.0
        Win32 Version: 4.0.30319.1 built by: RTMRel
        CodeBase: file:///C:/WINDOWS/Microsoft.Net/assembly/GAC_MSIL/System.Numerics/v4.0_4.0.0.0__b77a5c561934e089/System.Numerics.dll
    ----------------------------------------
    System.Windows.Forms
        Assembly Version: 4.0.0.0
        Win32 Version: 4.0.30319.1 built by: RTMRel
        CodeBase: file:///C:/WINDOWS/Microsoft.Net/assembly/GAC_MSIL/System.Windows.Forms/v4.0_4.0.0.0__b77a5c561934e089/System.Windows.Forms.dll
    ----------------------------------------
    System.Drawing
        Assembly Version: 4.0.0.0
        Win32 Version: 4.0.30319.1 built by: RTMRel
        CodeBase: file:///C:/WINDOWS/Microsoft.Net/assembly/GAC_MSIL/System.Drawing/v4.0_4.0.0.0__b03f5f7f11d50a3a/System.Drawing.dll
    ----------------------------------------
    Anonymously Hosted DynamicMethods Assembly
        Assembly Version: 0.0.0.0
        Win32 Version: 4.0.30319.225 (RTMGDR.030319-2200)
        CodeBase: file:///C:/WINDOWS/Microsoft.Net/assembly/GAC_32/mscorlib/v4.0_4.0.0.0__b77a5c561934e089/mscorlib.dll
    ----------------------------------------
    Accessibility
        Assembly Version: 4.0.0.0
        Win32 Version: 4.0.30319.1 built by: RTMRel
        CodeBase: file:///C:/WINDOWS/Microsoft.Net/assembly/GAC_MSIL/Accessibility/v4.0_4.0.0.0__b03f5f7f11d50a3a/Accessibility.dll
    ----------------------------------------
    Snippets.scripting
        Assembly Version: 0.0.0.0
        Win32 Version: 1.1.0.20
        CodeBase: file:///C:/WINDOWS/Microsoft.Net/assembly/GAC_MSIL/Microsoft.Dynamic/v4.0_1.1.0.20__7f709c5b713576e1/Microsoft.Dynamic.dll
    ----------------------------------------

    ************** JIT Debugging **************
    To enable just-in-time (JIT) debugging, the .config file for this
    application or computer (machine.config) must have the
    jitDebugging value set in the system.windows.forms section.
    The application must also be compiled with debugging
    enabled.

    For example:

    <configuration>
        <system.windows.forms jitDebugging="true" />
    </configuration>

    When JIT debugging is enabled, any unhandled exception
    will be sent to the JIT debugger registered on the computer
    rather than be handled by this dialog box.

  • 05-14-2011 11:51 PM In reply to

    • washad
    • Not Ranked
    • Joined on 05-14-2011
    • Posts 9

    Re: trying to connect to MYSQL DB

     

    Haven't connected to MySQL, but I'm connecting to a SQL Express DB in a current project. I also found something that looks similar on the web. I'll give them both to you and maybe you can make something out of them both. I hope it helps.....

     

     

    From Google:

    _____________________________________________________________________

    private void button1_Click(object sender, System.EventArgs e)
    {
    string MyConString = "SERVER=localhost;" +
    "DATABASE=mydatabase;" +
    "UID=testuser;" +
    "PASSWORD=testpassword;";
    MySqlConnection connection = new MySqlConnection(MyConString);
    MySqlCommand command = connection.CreateCommand();
    MySqlDataReader Reader;
    command.CommandText = "select * from mycustomers";
    connection.Open();
    Reader = command.ExecuteReader();
    while (Reader.Read())
    {
    string thisrow = "";
    for (int i= 0;i<Reader.FieldCount;i++)
    thisrow+=Reader.GetValue(i).ToString() + ",";
    listBox1.Items.Add(thisrow);
    }
    connection.Close();
    }
    
    
    _________________________________________________________________________
    
    
    
    
    My Working Code
    ________________________________________________________________________
    using System;
    using System.Data;
    using System.Data.SqlClient;
    using PakTech.Structures;
    using System.Collections.Generic;
    using System.Collections;
    
    
    namespace PakTech.Classes
    {
    	/// <summary>
    	/// Description of DB.
    	/// </summary>
    	public class Database
    	{
    		
    	
    		
    		SqlConnection connection;			// The connection to the database
    		
    		
    		string activeEventsQuery = "SELECT * FROM dbo.EVENT_LOG " +
    									   "WHERE dbo.EVENT_LOG.ELOG_OFF_DATE is null";
    		
    		enum Event_Log_Colums {
    			ELOG_ID,
    			EVENT_ID,
    			ELOG_ON_DATE,
    			ELOG_OFF_DATE
    		}
    		
    		DB_Configuration config;
    		
    		
    		/// <summary>
    		/// Consructor
    		/// </summary>
    		public Database(DB_Configuration config)
    		{
    			this.config = config;
    		}
    		
    		
    		
    		
    		
    		
    		// Method: CONNECT
    		// ******************************************************************8
    		/// <summary>
    		/// Connects to the database
    		/// </summary>
    		/// <param name="config">An instance of DB_Configuration that 
    		/// holds all of the database configuration information. </param>
    		public void Connect()
    		{
    			
    			try
    			{
    				// Build the connection string to the database. 
    				SqlConnectionStringBuilder _builder = new SqlConnectionStringBuilder();
    				_builder.DataSource = config.ConnectionString;
    				_builder.InitialCatalog = config.Database;
    				_builder.IntegratedSecurity = config.UseIntegratedSecurity;
    				
    				// Username and password may not be used if Windows Authentication is used
    				if (config.UserName != null && config.UserName.Length > 0) {
    					_builder.UserID = config.UserName;
    				}				
    				if (config.Password != null && config.Password.Length > 0) {
    					_builder.Password = config.Password;
    				}
    				
    				
    				// Create a new connection. 
    				connection = new SqlConnection(_builder.ConnectionString);
    				
    				// Test the connection. It is easier to troubleshoot if 
    				// the exeption is thrown in the connect method instead
    				// of later. 
    				connection.Open();
    				connection.Close();				
    				
    			}
    			catch (Exception Ex)
    			{
    				// TODO Add error handling
    				throw new NotImplementedException("Exeption not handled");
    			}
    			finally
    			{
    				closeConnection();
    			}
    			
    			
    		}
    		
    		
    		
    		
    		
    		
    		/// <summary>
    		/// Writes production values to the database
    		/// </summary>
    		/// <param name="productionValues">A list of production values to write</param>
    		/// <returns>
    		/// The number of rows affected</returns>
    		public int WriteProductionValues(ProductionValue[ productionValues)
    		{	
    			int _rowsEffected;
    			
    			try
    			{
    				connection.Open();
    				SqlCommand _sqlCmd = new SqlCommand();
    				_sqlCmd.Connection = connection;
    				
    				_sqlCmd.CommandText = "INSERT INTO dbo.PROD_VAL_LOG " + 
    				"(PVAL_ID, PVLOG_VALUE, PVLOG_DATE_STAMP) " +
    				"Values " +
    				"(@ID,@VALUE,@DATE)";
    				
    				_sqlCmd.Parameters.Add("ID", SqlDbType.Int);
    				_sqlCmd.Parameters.Add("VALUE", SqlDbType.Int);
    				_sqlCmd.Parameters.Add("DATE", SqlDbType.DateTime);
    				
    				
    				foreach (ProductionValue _pval in productionValues)
    				{
    					_sqlCmd.Parameters["ID"].Value = _pval.ID;
    					_sqlCmd.Parameters["VALUE"].Value = _pval.CurrentValue;
    					_sqlCmd.Parameters["DATE"].Value = _pval.ValueDate;
    					
    					_sqlCmd.ExecuteNonQuery();
    				}
    			
    				_rowsEffected = productionValues.Length;
    				
    				
    			}
    			catch (Exception Ex)
    			{
    			 	// TODO: Error handling
    			 	throw new NotImplementedException("Need to handle error");
    			}
    			finally 
    			{
    				closeConnection();
    			}
    			
    			
    			return _rowsEffected;
    			
    
    			
    			
    		}
    		
    		
    		
    		
    		
    		
    		
    		// Method:			GET ACTIVE EVENTS
    		// ***********************************************************
    		/// <summary>
    		/// Gets a list of events that are currently active. Active
    		/// events are defined as any event in the event log with 
    		/// a null off date. Recall that the on-date has to be set at
    		/// the time that the event is written to the database. 
    		/// </summary>
    		/// <returns>
    		/// An array of events that are currently active
    		/// </returns>
    		/// 
    		public Event[ GetActiveEvents()
    		{
    			
    			SqlDataReader _reader = null;			// The reader used to get the data.
    			List<Event> _activeEvents = null;
    			
    			try
    			{
    				connection.Open();
    				
    				// Query the DB for active events. 
    				SqlCommand _command = connection.CreateCommand();				
    				_command.CommandText = activeEventsQuery;
    				_reader = _command.ExecuteReader();
    				
    				
    				if (_reader.HasRows)
    				{			
    					_activeEvents = new List<Event>();
    					
    					// Fill the event array;					
    					while (_reader.Read())
    					{
    						int _eventId = (int)_reader[Event_Log_Colums.EVENT_ID.ToString()];
    						DateTime _onDate = (DateTime)_reader[Event_Log_Colums.ELOG_ON_DATE.ToString()];
    											                                     
    						Event _event = new Event();					
    						_event.ID = _eventId;
    						_event.IsOn = true;
    						_event.OverrideOnDate(_onDate);
    						
    						_activeEvents.Add(_event);
    					}
    				}			
    				
    				
    			}
    			
    			
    			catch (Exception Ex)
    			{
    				Console.WriteLine(Ex.Message);
    			}
    			
    			
    			finally
    			{
    				closeConnection();
    				if (_reader != null)
    				{
    					if (_reader.IsClosed != true)
    					{
    						_reader.Close();
    					}
    				}		
    			}
    			
    			return _activeEvents.ToArray();
    			
    		}
    		
    		
    		
    		
    		
    		
    		/// <summary>
    		/// Closes the connection to the database. 
    		/// </summary>
    		private void closeConnection()
    		{
    			if (connection != null)
    			{ 
    				if (connection.State == ConnectionState.Open)
    				{
    					connection.Close();
    				}
    			}
    		}
    		
    		
    		
    		
    	}
    }

  • 05-15-2011 10:21 AM In reply to

    Re: trying to connect to MYSQL DB

    It looks like you are mixing VB.NET code with IronRuby which is not going to work. The error message is because the IronRuby runtime is looking at a VB.NET try-catch block and is expecting a begin-rescue block. You'll need to port the code to IronRuby. You could try running it through the VB.NET to IronRuby converter.

Page 1 of 1 (3 items)
Powered by Community Server (Commercial Edition), by Telligent Systems
Don't contact us via this (fleischfalle@alphasierrapapa.com) email address.