8
private void button1_Click(object sender, EventArgs e)
{
    try
    {
        SqlConnection conn = new SqlConnection();
        conn.ConnectionString = "Data Source=*******;Initial Catalog=ChatApp;User ID=Chatapplication;Password=****";
        conn.Open();
        SqlCommand cmd = new SqlCommand();
        string chatroomidno = textBox1.Text;
        string chatroomname = textBox2.Text;
        //cmd.CommandText = "Select ChatRoomID=@ChatRoomID,ChatRoomName=@ChatRoomName from tblChatRoom";
        //cmd.Connection = conn;
        SqlDataAdapter adapt = new SqlDataAdapter("Chatroomapp",conn);
        adapt.SelectCommand.CommandType = CommandType.StoredProcedure;
        DataSet ds=new DataSet();
        DataTable dt = new DataTable();
        adapt.SelectCommand.Parameters.Add(new SqlParameter("@ChatRoomID", SqlDbType.VarChar, 100));
        adapt.SelectCommand.Parameters["@ChatRoomID"].Value = chatroomidno;
        adapt.SelectCommand.Parameters.Add(new SqlParameter("@ChatRoomName", SqlDbType.VarChar, 50));
        adapt.SelectCommand.Parameters["@ChatRoomName"].Value = chatroomname;
        adapt.Fill(ds, "tblChatRoom");
        if (dt.Rows.Count > 0)
        {
            MessageBox.Show("Connection Succedded");
        }
        else
        {
            MessageBox.Show("Connection Fails");
        }
    }
    catch (Exception ex)
    {
        MessageBox.Show("Error", ex.Message);
    }
}

While compiling the program I got only connection fails message box, in the database. I found correct, how to overcome the program to get the connection succeeded message box.

4

2 回答 2

14

好吧,您正在填充ds数据集 - 但随后您正在检查dt数据表中是否存在行......当然,这永远不会奏效!

如果您只需要一个DataTable- 只需单独使用和填充该数据表 - 不需要DataSet. 另外,将你的SqlConnectionandSqlCommand放入使用这样的块中:

using (SqlConnection conn = new SqlConnection("Data Source=*******;Initial Catalog=ChatApp;User ID=Chatapplication;Password=****"))
using (SqlCommand cmd = new SqlCommand("Chatroomapp", conn))
{
    string chatroomidno = textBox1.Text;
    string chatroomname = textBox2.Text;

    SqlDataAdapter adapt = new SqlDataAdapter(cmd);
    adapt.SelectCommand.CommandType = CommandType.StoredProcedure;
    adapt.SelectCommand.Parameters.Add(new SqlParameter("@ChatRoomID", SqlDbType.VarChar, 100));
    adapt.SelectCommand.Parameters["@ChatRoomID"].Value = chatroomidno;
    adapt.SelectCommand.Parameters.Add(new SqlParameter("@ChatRoomName", SqlDbType.VarChar, 50));
    adapt.SelectCommand.Parameters["@ChatRoomName"].Value = chatroomname;

    // fill the data table - no need to explicitly call `conn.Open()` - 
    // the SqlDataAdapter automatically does this (and closes the connection, too)
    DataTable dt = new DataTable();
    adapt.Fill(dt);

    if (dt.Rows.Count > 0)
    {
       MessageBox.Show("Connection Succedded");
    }
    else
    {
       MessageBox.Show("Connection Fails");
    }
}

并且仅仅因为您没有返回任何行dt.Rows并不一定意味着您的连接失败......可能只是没有符合您的搜索条件的行!连接工作得很好——但 SQL 命令没有返回任何行。

于 2013-08-04T10:23:53.700 回答
0

连接失败意味着您的程序和数据库之间出现了问题。没有返回记录并不意味着连接失败。这只是意味着您的表是空的 - 它不包含任何记录。

使用ADO.NETand astored procedures会与您所做的有所不同。如果您需要检查连接是否失败,也许最好检查catch部件中返回的异常类型。

下面是我将如何做到的。我会创建一个单独的方法来处理我的调用,然后在你的button1_Click我会调用这个方法:

public async Task<ChatRoom> GetAsync(string chatRoomId, string chatRoomName)
{
     try
     {
          string connectionString = ConfigurationManager.ConnectionStrings["Db"].ConnectionString;

          using (SqlConnection sqlConnection = new SqlConnection(connectionString))
          {
               await sqlConnection.OpenAsync();

               using (SqlCommand sqlCommand = new SqlCommand("ChatRooms_Get", sqlConnection))
               {
                    sqlCommand.CommandType = CommandType.StoredProcedure;
                    sqlCommand.Parameters.Add(new SqlParameter("@ChatRoomID", chatRoomId));
                    sqlCommand.Parameters.Add(new SqlParameter("@ChatRoomName", chatRoomName));

                    using (SqlDataReader sqlDataReader = await sqlCommand.ExecuteReaderAsync())
                    {
                         ChatRoom chatRoom = null;

                         if (await sqlDataReader.ReadAsync())
                         {
                              chatRoom = new ChatRoom();
                              chatRoom.Id = sqlDataReader.GetFieldValue<string>(0);
                              chatRoom.Name = sqlDataReader.GetFieldValue<string>(1);

                              chatRooms.Add(chatRoom);
                         }

                         return chatRoom;
                    }
               }
          }
     }
     catch (Exception exception)
     {
          // Try checking if the connection failed here

          throw exception;
     }
}

我的聊天室domain model可能看起来像这样:

public class ChatRoom
{
     public string Id { get; set; }

     public string Name { get; set; }
}

存储过程看起来像这样:

CREATE PROCEDURE [dbo].[ChatRooms_Get]
(
     @ChatRoomID VARCHAR(100),
     @ChatRoomName VARCHAR(50)
)
AS
BEGIN
     SET NOCOUNT ON;

     SELECT
          ChatRoomID,
          ChatRoomName
     FROM
          tblChatRoom
     WHERE
          ChatRoomID = @ChatRoomID
          AND ChatRoomName = @ChatRoomName;
END

GO

然后在调用方法中,您将获得聊天室并使用它做任何您需要做的事情。对于这个例子,我只是检查了它是否存在:

try
{
     ChatRoom chatRoom = await chatRoomRepository.GetAsync(chatRoomId, chatRoomName);
     if (chatRoom != null)
     {
          MessageBox.Show("Record found");
     }
     else
     {
          MessageBox.Show("No record found");
     }
}
catch (Exception exception)
{
     throw exception;
}

我希望这会有所帮助。

于 2016-05-18T10:44:01.810 回答