“连接必须有效且开放”

时间:2016-01-17 23:06:51

标签: c# mysql asp.net

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

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()时会出现问题;

1 个答案:

答案 0 :(得分:1)

您必须在使用此代码

调用ExecuteNonQuery之前打开连接
 cn.Open();

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

 cn.Close();