“连接必须有效且打开”

本文关键字:有效 连接 | 更新日期: 2023-09-27 18:30:48

我有这个错误,我一直在看谷歌和这里的另一个问题,我找不到我的问题的答案,这是我的代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Net.Http;
using System.Web.Http;
using MySql.Data.MySqlClient;
namespace WebService1
{
    /// <summary>
    /// Descripción breve de Service1
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    // Para permitir que se llame a este servicio web desde un script, usando ASP.NET AJAX, quite la marca de comentario de la línea siguiente. 
    // [System.Web.Script.Services.ScriptService]
    public class Service1 : System.Web.Services.WebService
    {
        [WebMethod]
        public string HelloWorld()
        {
            return "Hola a todos";
        }

        [WebMethod]
        public string ConectarBaseDatos()
        {
            try
            {
                using (MySqlCommand cm = new MySqlCommand())
                {
                    string connection = @"Data Source=localhost:3306; Database=sistemadatosatletasfecovol; 
                                User ID=movil; Password=***";
                    MySqlConnection cn = new MySqlConnection(connection);

                    cm.CommandType = System.Data.CommandType.StoredProcedure;
                    cm.CommandText = "ingresarUsuario";
                    cm.Parameters.Add("_email", MySqlDbType.VarChar).Value = "asdasd@gmail.com";
                    cm.Parameters.Add("_password", MySqlDbType.VarChar).Value = "******";
                    cm.Connection = cn;
                    cm.ExecuteNonQuery();
                    MySqlDataReader cr = cm.ExecuteReader();
                    cr.Read();
                    string id;
                    id = cr["idUsuario"].ToString();
                    return id;
                }
            }
            catch (Exception ex)
            {
                return ex.ToString();
            }
        }
    }
}

在网络上的方法"ConectarBaseDatos",当我执行cm.ExecuteNonQuery()时出现问题;

“连接必须有效且打开”

在使用此代码调用 ExecuteNonQuery 之前,必须打开连接

 cn.Open();

然后,确保在 using 块的末尾使用此代码关闭连接:

 cn.Close();