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

时间:2015-02-09 19:03:35

标签: 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" 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>

IServiceAPI.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);
    }
}

ServiceAPI.CS

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);

        }
    }
}

1 个答案:

答案 0 :(得分:1)

您的IsServerConnected方法为staticNote:如果连接为open并且您尝试打开它,那么请确保您获得例外,我的意思是对于开放连接connection.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)
                     {
                     }
                }
            }
        }