简体   繁体   中英

How to call a stored procedure using ADO.NET?

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.

Well, you're filling the ds data set - but then you're checking the dt data table for presence of rows... that's never going to work, of course!

If you only need a single DataTable - just use and fill that data table alone - no need for the overhead of a DataSet . Also, put your SqlConnection and SqlCommand into using blocks like this:

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

And just because you get back no rows in dt.Rows doesn't necessarily mean that your connection failed..... it could just be that there are no rows that match your search critieria! The connection worked just fine - but the SQL command just didn't return any rows.

Connection failed means that something went wrong between your program and the database. No records returned does not mean that the connection failed. It just means that your table is empty - it contains no records.

Using ADO.NET and a stored procedures would have been a little different from what you have done it. If you need to check if the connection failed, maybe it is better to check the type of exception that is returned in the catch part.

Below is how I would have done it. I would have created a separate method that would have handled my call, and then in your button1_Click I would have just called this method:

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

My chat room domain model could have looked like this:

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

     public string Name { get; set; }
}

And the stored procedure would have looked like this:

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

And then in the calling method you would get the chatroom and do with it whatever you need to do with it. For this example I just checked if it exists or not:

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

I hope this can help.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM