从C#ASP WEB应用程序测试SQL连接

从C#ASP WEB应用程序测试SQL连接,c#,sql,asp.net,sql-server,C#,Sql,Asp.net,Sql Server,我是一名C#编程新手,正在尝试让REST API正常工作。出于某种原因,它没有从iOS连接,我想测试SQL连接,以便首先从该点排除连接故障。我怎样才能开始测试它呢?我试图弄明白,但我对C#的理解仍然很有限 代码如下: Web.config <?xml version="1.0" encoding="utf-8"?> <configuration> <system.web> <compilation debug="true" targetFra

我是一名C#编程新手,正在尝试让REST API正常工作。出于某种原因,它没有从iOS连接,我想测试SQL连接,以便首先从该点排除连接故障。我怎样才能开始测试它呢?我试图弄明白,但我对C#的理解仍然很有限

代码如下:

Web.config

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <system.web>
    <compilation debug="true" targetFramework="4.5" />
    <httpRuntime targetFramework="4.5" />
  </system.web>
  <connectionStrings>
    <add name="conString" connectionstring="Data Source=10.0.0.1;Initial Catalog=DBName;Password=Password;User ID=UserID;Integrated Security=True;" providername="System.Data.SqlClient"/>
  </connectionStrings>
</configuration>
ServiceAPI.CS

using System.Data;

namespace RESTWebAPI
{
    // This interface declare the methods need to be implement.
    public interface IServiceAPI
    {
        void CreateNewAccount(string username, string password);
        DataTable Getmembers(string username);
        bool UserAuthentication(string username, string passsword);
    }
}
using System;
using System.Data;
using System.Data.SqlClient;
using Web.config;

namespace RESTWebAPI
{
        public static bool IsServerConnected(string connectionString)
        {
            using (SqlConnection connection = new SqlConnection(connectionString))
            {
                try
                {
                    connection.Open();
                    return true;
                }
                catch (SqlException)
                {
                    return false;
                }
            }
        }

    public class ServiceAPI : IServiceAPI
    {
        SqlConnection dbConnection;

        public ServiceAPI()
        {
            dbConnection = DBConnect.getConnection();
        }

        public void CreateNewAccount(string username, string password)
        {
            if (dbConnection.State.ToString() == "Closed")
            {
                dbConnection.Open();
            }
            string query = "INSERT INTO members VALUES ('" + username + "','" + password + "');";
            SqlCommand command = new SqlCommand(query, dbConnection);
            command.ExecuteNonQuery();
            dbConnection.Close();
        }

        public DataTable Getmembers(string username)
        {
            DataTable membersTable = new DataTable();
            membersTable.Columns.Add(new DataColumn("username", typeof(String)));

            if (dbConnection.State.ToString() == "Closed")
            {
                dbConnection.Open();
            }

            string query = "SELECT username FROM members WHERE username='" + username + "';";
            SqlCommand command = new SqlCommand(query, dbConnection);
            SqlDataReader reader = command.ExecuteReader();

            if (reader.HasRows)
            {
                while (reader.Read())
                {
                    membersTable.Rows.Add(reader["username"]);
                }
            }
            reader.Close();
            dbConnection.Close();
            return membersTable;
        }

        public bool UserAuthentication(string username, string passsword)
        {
            bool auth = false;

            if (dbConnection.State.ToString() == "Closed")
            {
                dbConnection.Open();
            }
            string query = "SELECT id FROM members WHERE username='" + username + "' AND password='" + passsword + "';";

            SqlCommand command = new SqlCommand(query, dbConnection);
            SqlDataReader reader = command.ExecuteReader();

            if (reader.HasRows)
            {
                auth = true;
            }
            reader.Close();
            dbConnection.Close();
            return auth;
        }
    }
}
DBConnect.cs

using System.Configuration;
using System.Data.SqlClient;

namespace RESTWebAPI
{
    // This class is used to connect to sql server database
    public class DBConnect
    {
        private static SqlConnection NewCon;
        private static string conStr = ConfigurationManager.ConnectionStrings["ConString"].ConnectionString;

        public static SqlConnection getConnection()
        {
            NewCon = new SqlConnection(conStr);
            return NewCon;
        }

        public DBConnect()
        {
        }
    }
}
Handler1.ashx.cs

using JsonServices;
using JsonServices.Web;

namespace RESTWebAPI
{
    public class Handler1 : JsonHandler
    {
        public Handler1()
        {
            this.service.Name = "RESTWebAPI";
            this.service.Description = "JSON API for mobile application";
            InterfaceConfiguration IConfig = new InterfaceConfiguration("RestAPI", typeof(IServiceAPI), typeof(ServiceAPI));
            this.service.Interfaces.Add(IConfig);

        }
    }
}

您的
IsServerConnected
方法是
static
注意:
如果连接是
打开的
,并且您尝试打开它,那么您肯定会得到一个异常,我指的是打开的连接
连接.open()
引发异常,因此如果IsServerConnected方法仅用于检查连接,则在打开连接后需要finally块来关闭连接:

public static bool IsServerConnected(string connectionString)
        {
            using (SqlConnection connection = new SqlConnection(connectionString))
            {
                try
                {
                    connection.Open();
                    return true;
                }
                catch (SqlException)
                {
                    return false;
                }
                finally
                {
                    try
                     {
                         connection.Close();
                     }
                     catch (Exception ex)
                     {
                     }
                }
            }
        }

catch(SqlException){returnfalse;}
您知道捕获异常的意义吗?通过尝试其他方法或记录问题来处理它们。但是你没有做这两件事,所以你不知道错误是什么。既然你不知道错误是什么,你就不能告诉我们。现在,只需删除try/catch并查看错误消息是什么,然后用这些信息更新您的问题。我已经清理了您的代码以删除大量的空行。为了帮助您的人,请在发布到堆栈溢出时删除此代码。对于格式错误,我深表歉意。谢谢你的帮助。谢谢,这正是我需要的。