简体   繁体   English

如何使用 ADO.NET 调用存储过程?

[英]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!好吧,您正在填充ds数据集 - 但随后您正在检查dt数据表中是否存在行……当然,这永远不会起作用!

If you only need a single DataTable - just use and fill that data table alone - no need for the overhead of a DataSet .如果您只需要一个DataTable - 只需单独使用和填充该数据表 - 不需要DataSet的开销。 Also, put your SqlConnection and SqlCommand into using blocks like this:此外,将您的SqlConnectionSqlCommand放入使用这样的块:

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!仅仅因为您在dt.Rows中没有返回任何行并不一定意味着您的连接失败......可能只是没有符合您的搜索条件的行! The connection worked just fine - but the SQL command just didn't return any rows.连接工作得很好——但 SQL 命令没有返回任何行。

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.使用ADO.NETstored procedures会与您所做的有所不同。 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.如果需要检查连接是否失败,最好检查catch部分中返回的异常类型。

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:我会创建一个单独的方法来处理我的调用,然后在你的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;
     }
}

My chat room domain model could have looked like this:我的聊天室domain model可能看起来像这样:

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.我希望这会有所帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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