Foros del Web » Programación para mayores de 30 ;) » .NET »

Problemas con C#

Estas en el tema de Problemas con C# en el foro de .NET en Foros del Web. Tengo el código este. En MySQL me funciona bajo phpMyAdmin este código sin problemas pero no Visual C#. ¿Cómo lo soluciono? Código: private void button_actualizar_Click(object ...
  #1 (permalink)  
Antiguo 15/07/2009, 14:00
 
Fecha de Ingreso: mayo-2007
Ubicación: PIC-16F84A
Mensajes: 727
Antigüedad: 16 años, 11 meses
Puntos: 8
Problemas con C#

Tengo el código este. En MySQL me funciona bajo phpMyAdmin este código sin problemas pero no Visual C#. ¿Cómo lo soluciono?

Código:
private void button_actualizar_Click(object sender, EventArgs e)
        {
            string insertar_disp = @"UPDATE `dispositivos` SET descripcion='descripcion1' WHERE id='1';
                                     UPDATE `dispositivos` SET descripcion='descripcion2' WHERE id='2';
                                     UPDATE `dispositivos` SET descripcion='descripcion3' WHERE id='3';
                                     UPDATE `dispositivos` SET descripcion='descripcion4' WHERE id='4';";
                                            

            connection = new MySqlConnection(MyConString);
            MySqlCommand con7 = new MySqlCommand(insertar_disp, connection);
            connection.Open();
            con7.ExecuteNonQuery();
            connection.Close();
        }

Datos de MySQL es:
Código:
CREATE TABLE IF NOT EXISTS `dispositivos` (
  `ID` int(11) NOT NULL AUTO_INCREMENT,
  `nombre` varchar(6) COLLATE latin1_spanish_ci NOT NULL,
  `estado` tinyint(2) NOT NULL,
  `descripcion` varchar(20) COLLATE latin1_spanish_ci NOT NULL,
  PRIMARY KEY (`ID`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 COLLATE=latin1_spanish_ci AUTO_INCREMENT=5 ;

--
-- (Evento) desencadenante `dispositivos`
--
DROP TRIGGER IF EXISTS `pic_remoto`.`logestado`;
DELIMITER //
CREATE TRIGGER `pic_remoto`.`logestado` AFTER UPDATE ON `pic_remoto`.`dispositivos`
 FOR EACH ROW BEGIN

                                   DECLARE Rele1 INT;
                                   DECLARE Rele2 INT;
                                   DECLARE Rele3 INT;
                                   DECLARE Rele4 INT;

                                   SET Rele1 = (SELECT estado
                                   FROM dispositivos
                                   WHERE nombre LIKE 'RELE 1');

                                   SET Rele2 = (SELECT estado
                                   FROM dispositivos
                                   WHERE nombre LIKE 'RELE 2');

                                   SET Rele3 = (SELECT estado
                                   FROM dispositivos
                                   WHERE nombre LIKE 'RELE 3');

                                   SET Rele4 = (SELECT estado
                                   FROM dispositivos
                                   WHERE nombre LIKE 'RELE 4');

                                   INSERT INTO log(RELE_1, RELE_2, RELE_3, RELE_4, USUARIO, FECHA_HORA)
                                   VALUES (Rele1, Rele2, Rele3, Rele4, USER(), NOW());
                             END
//
DELIMITER ;

--
-- Volcar la base de datos para la tabla `dispositivos`
--

INSERT INTO `dispositivos` (`ID`, `nombre`, `estado`, `descripcion`) VALUES
(1, 'RELÉ 1', 0, 'vacío'),
(2, 'RELÉ 2', 0, 'vacío'),
(3, 'RELÉ 3', 0, 'vacío'),
(4, 'RELÉ 4', 0, 'vacío');
Me da error:
No se controló System.ArgumentNullException
Message="La clave no puede ser nula.\r\nNombre del parámetro: key"
Source="mscorlib"
ParamName="key"
StackTrace:
en System.Collections.Hashtable.get_Item(Object key)
en MySql.Data.MySqlClient.MySqlPoolManager.GetPool(My SqlConnectionStringBuilder settings)
en MySql.Data.MySqlClient.MySqlConnection.Open()
en MySQL12.Form1.button_actualizar_Click(Object sender, EventArgs e) en C:\Documents and Settings\Hunter\Mis documentos\Visual Studio 2008\Projects\MySQL12\MySQL12\Form1.cs:línea 157
en System.Windows.Forms.Control.OnClick(EventArgs e)
en System.Windows.Forms.Button.OnClick(EventArgs e)
en System.Windows.Forms.Button.OnMouseUp(MouseEventAr gs mevent)
en System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons button, Int32 clicks)
en System.Windows.Forms.Control.WndProc(Message& m)
en System.Windows.Forms.ButtonBase.WndProc(Message& m)
en System.Windows.Forms.Button.WndProc(Message& m)
en System.Windows.Forms.Control.ControlNativeWindow.O nMessage(Message& m)
en System.Windows.Forms.Control.ControlNativeWindow.W ndProc(Message& m)
en System.Windows.Forms.NativeWindow.DebuggableCallba ck(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
en System.Windows.Forms.UnsafeNativeMethods.DispatchM essageW(MSG& msg)
en System.Windows.Forms.Application.ComponentManager. System.Windows.Forms.UnsafeNativeMethods.IMsoCompo nentManager.FPushMessageLoop(Int32 dwComponentID, Int32 reason, Int32 pvLoopData)
en System.Windows.Forms.Application.ThreadContext.Run MessageLoopInner(Int32 reason, ApplicationContext context)
en System.Windows.Forms.Application.ThreadContext.Run MessageLoop(Int32 reason, ApplicationContext context)
en System.Windows.Forms.Application.Run(Form mainForm)
en MySQL12.Program.Main() en C:\Documents and Settings\Hunter\Mis documentos\Visual Studio 2008\Projects\MySQL12\MySQL12\Program.cs:línea 18
en System.AppDomain._nExecuteAssembly(Assembly assembly, String[] args)
en System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
en Microsoft.VisualStudio.HostingProcess.HostProc.Run UsersAssembly()
en System.Threading.ThreadHelper.ThreadStart_Context( Object state)
en System.Threading.ExecutionContext.Run(ExecutionCon text executionContext, ContextCallback callback, Object state)
en System.Threading.ThreadHelper.ThreadStart()
InnerException:
__________________
Meta Shell, VERSIÓN 1.2.2
Descargar
  #2 (permalink)  
Antiguo 16/07/2009, 11:46
Avatar de atak  
Fecha de Ingreso: julio-2005
Ubicación: Huancayo
Mensajes: 490
Antigüedad: 18 años, 9 meses
Puntos: 5
De acuerdo Respuesta: Problemas con C#

hola,
te recomiendo que hagas pruebas parciales.

Conexion.

Ejecucion de codigos SQL desde C# hacia MySQL.

y se que por ahi detectaras el problema.


Atte,
atak
__________________
. .: El mejor Inicio :. .
  #3 (permalink)  
Antiguo 16/07/2009, 11:56
 
Fecha de Ingreso: mayo-2007
Ubicación: PIC-16F84A
Mensajes: 727
Antigüedad: 16 años, 11 meses
Puntos: 8
Respuesta: Problemas con C#

Te dejo el código.

Código:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using MySql.Data.MySqlClient; // No olvidar este using.
using MySql.Data.Types;       // No olvidar este using.

namespace MySQL12
{
    public partial class Form1 : Form
    {
        MySqlConnection connection = null; // No olvidar.
        string MyConString;

        public Form1()
        {
            InitializeComponent();
        }

        private void button_crear_bd_Click(object sender, EventArgs e)
        {
            #region Bases de datos.
            string MyConString = "SERVER=" + textBox_Servidor.Text + ";" +
                "UID=" + textBox_Usuario.Text + ";" +
                "PASSWORD=" + textBox_Contraseña.Text + ";";
                                                                        // Aquí va 'pic_remoto'.
            string bd_pic_remoto = "CREATE DATABASE IF NOT EXISTS `" + textBox_Base_de_datos.Text + @"`DEFAULT CHARACTER SET latin1 COLLATE latin1_spanish_ci;
                                   USE `" + textBox_Base_de_datos.Text + "`;";

            connection = new MySqlConnection(MyConString);
            MySqlCommand con = new MySqlCommand(bd_pic_remoto, connection);
            connection.Open();
            con.ExecuteNonQuery();
            connection.Close();

            // Estructura de tabla para la tabla `dispositivos`
            string tb_dispositivos = "CREATE TABLE IF NOT EXISTS `" + textBox_dispositivo.Text + @"` (
                                     `ID` int(11) NOT NULL AUTO_INCREMENT,
                                     `nombre` varchar(6) COLLATE latin1_spanish_ci NOT NULL,
                                     `estado` tinyint(2) NOT NULL,
                                     `descripcion` varchar(20) COLLATE latin1_spanish_ci NOT NULL,
                                     PRIMARY KEY (`ID`)
                                     ) ENGINE=InnoDB  DEFAULT CHARSET=latin1 COLLATE=latin1_spanish_ci AUTO_INCREMENT=5;";

            connection = new MySqlConnection(MyConString);
            MySqlCommand con2 = new MySqlCommand(tb_dispositivos, connection);
            connection.Open();
            con2.ExecuteNonQuery();
            connection.Close();

            // (Evento) desencadenante `dispositivos`
            string drop_trigger = "DROP TRIGGER IF EXISTS `" + textBox_Base_de_datos.Text + "`.`logestado`;";

            connection = new MySqlConnection(MyConString);
            MySqlCommand con3 = new MySqlCommand(drop_trigger, connection);
            connection.Open();
            con3.ExecuteNonQuery();
            connection.Close();

            string trigger = "CREATE TRIGGER `" + textBox_Base_de_datos.Text + "`.`logestado` AFTER UPDATE ON `" + textBox_Base_de_datos.Text + "`.`" + textBox_dispositivo.Text + @"`
                             FOR EACH ROW BEGIN

                                   DECLARE Rele1 INT;
                                   DECLARE Rele2 INT;
                                   DECLARE Rele3 INT;
                                   DECLARE Rele4 INT;

                                   SET Rele1 = (SELECT estado
                                   FROM dispositivos
                                   WHERE nombre LIKE 'RELE 1');

                                   SET Rele2 = (SELECT estado
                                   FROM dispositivos
                                   WHERE nombre LIKE 'RELE 2');

                                   SET Rele3 = (SELECT estado
                                   FROM dispositivos
                                   WHERE nombre LIKE 'RELE 3');

                                   SET Rele4 = (SELECT estado
                                   FROM dispositivos
                                   WHERE nombre LIKE 'RELE 4');

                                   INSERT INTO " + textBox_log.Text + @"(RELE_1, RELE_2, RELE_3, RELE_4, USUARIO, FECHA_HORA)
                                   VALUES (Rele1, Rele2, Rele3, Rele4, USER(), NOW());
                             END";

            connection = new MySqlConnection(MyConString);
            MySqlCommand con4 = new MySqlCommand(trigger, connection);
            connection.Open();
            con4.ExecuteNonQuery();
            connection.Close();

            // Volcar la base de datos para la tabla `dispositivos`
            string insertar_datos = "INSERT INTO `" + textBox_dispositivo.Text + @"` (`ID`, `nombre`, `estado`, `descripcion`) VALUES
                                        (1, 'RELÉ 1', 0, ' '),
                                        (2, 'RELÉ 2', 0, ' '),
                                        (3, 'RELÉ 3', 0, ' '),
                                        (4, 'RELÉ 4', 0, ' ');";

            connection = new MySqlConnection(MyConString);
            MySqlCommand con5 = new MySqlCommand(insertar_datos, connection);
            connection.Open();
            con5.ExecuteNonQuery();
            connection.Close();

            // Estructura de tabla para la tabla `log`
            string log = "CREATE TABLE IF NOT EXISTS `" + textBox_log.Text + @"` (
                              `ID` int(11) NOT NULL AUTO_INCREMENT,
                              `RELE_1` tinyint(1) NOT NULL,
                              `RELE_2` tinyint(1) NOT NULL,
                              `RELE_3` tinyint(1) NOT NULL,
                              `RELE_4` tinyint(1) NOT NULL,
                              `USUARIO` varchar(40) COLLATE latin1_spanish_ci NOT NULL,
                              `FECHA_HORA` datetime NOT NULL,
                              PRIMARY KEY (`ID`)
                            ) ENGINE=InnoDB DEFAULT CHARSET=latin1 COLLATE=latin1_spanish_ci AUTO_INCREMENT=1;";

            connection = new MySqlConnection(MyConString);
            MySqlCommand con6 = new MySqlCommand(log, connection);
            connection.Open();
            con6.ExecuteNonQuery();
            connection.Close();

            // Deshabilitar.
            button_crear_bd.Enabled = false;
            textBox_Base_de_datos.Enabled = false;
            textBox_dispositivo.Enabled = false;
            textBox_log.Enabled = false;
            textBox_descripcion_rele1.Enabled = true;
            textBox_descripcion_rele2.Enabled = true;
            textBox_descripcion_rele3.Enabled = true;
            textBox_descripcion_rele4.Enabled = true;

            #endregion
        }

        private void button_aplicar_config_Click(object sender, EventArgs e)
        {
            groupBox2.Visible = true;
        }

        private void button_actualizar_Click(object sender, EventArgs e)
        {
            string insertar_disp = @"UPDATE `dispositivos` SET descripcion='descripcion1' WHERE id='1';
                                     UPDATE `dispositivos` SET descripcion='descripcion2' WHERE id='2';
                                     UPDATE `dispositivos` SET descripcion='descripcion3' WHERE id='3';
                                     UPDATE `dispositivos` SET descripcion='descripcion4' WHERE id='4';";
                                            

            connection = new MySqlConnection(MyConString);
            MySqlCommand con7 = new MySqlCommand(insertar_disp, connection);
            connection.Open();
            con7.ExecuteNonQuery();
            connection.Close();

            // Deshabilitar.
            button_actualizar.Enabled = false;
        }

        private void button_borrar_bd_Click(object sender, EventArgs e)
        {
            string borrar_bd = @"DROP DATABASE pic_remoto;"; // " + textBox_Base_de_datos.Text + "

            connection = new MySqlConnection(MyConString);
            MySqlCommand con8 = new MySqlCommand(borrar_bd, connection);
            connection.Open();
            con8.ExecuteNonQuery();
            connection.Close();
        }

        private void button_limpiar_Click(object sender, EventArgs e)
        {
            textBox_Base_de_datos.Clear();
            textBox_dispositivo.Clear();
            textBox_log.Clear();
            textBox_descripcion_rele1.Clear();
            textBox_descripcion_rele2.Clear();
            textBox_descripcion_rele3.Clear();
            textBox_descripcion_rele4.Clear();
            button_predeterminado.Enabled = true;
        }

        private void button_predeterminado_Click(object sender, EventArgs e)
        {
            textBox_Base_de_datos.Text = "pic_remoto";
            textBox_dispositivo.Text = "dispositivos";
            textBox_log.Text = "log";
            button_predeterminado.Enabled = false;
        }
    }
}
__________________
Meta Shell, VERSIÓN 1.2.2
Descargar
  #4 (permalink)  
Antiguo 16/07/2009, 21:29
Avatar de dwaks  
Fecha de Ingreso: agosto-2002
Ubicación: Panamá
Mensajes: 962
Antigüedad: 21 años, 8 meses
Puntos: 15
Respuesta: Problemas con C#

Solo como consejo, cuando son muchos update, insert ó delete que se hacen lo mejor es usar Transactions y no abrir y cerrar conección por cada query que se mande a la base de datos.

Aquí dejo información sobre eso, es SqlTransaction pero aplica igual para Mysql:
http://support.microsoft.com/kb/821766/es
  #5 (permalink)  
Antiguo 17/07/2009, 05:48
 
Fecha de Ingreso: mayo-2007
Ubicación: PIC-16F84A
Mensajes: 727
Antigüedad: 16 años, 11 meses
Puntos: 8
Respuesta: Problemas con C#

Puedes descargarte el proyecto completo aquí.

¿Se puede hacer con una única conexión?

DESCARGAR proyecto completo.

Para los que no sepan instalar MySQL 5.1, miren en la página 97 de este manual en PDF.

http://www.abcdatos.com/webmasters/tutorial/v310.html

Saludo.
__________________
Meta Shell, VERSIÓN 1.2.2
Descargar
Atención: Estás leyendo un tema que no tiene actividad desde hace más de 6 MESES, te recomendamos abrir un Nuevo tema en lugar de responder al actual.
Respuesta




La zona horaria es GMT -6. Ahora son las 13:00.