I am working at gaining an understanding at how to interface stored procedures with applications. My example is simple, but it doesn’t display my columns and rows in the command prompt, instead it display System.Data.SqlClient.SqlDataReader. How do I display the rows from my stored procudure?
----Stored Proc--
ALTER PROCEDURE dbo.SelectID
AS
SELECT * FROM tb_User;
-----
Below is the code:
using System;
using System.Data.SqlClient;
using System.IO;
namespace ExecuteStoredProc
{
class Program
{
static void Main(string[] args)
{
SqlConnection cnnUserMan;
SqlCommand cmmUser;
//SqlDataReader drdUser;
//Instantiate and open the connection
cnnUserMan = new SqlConnection("Data Source=.\\SQLEXPRESS;AttachDbFilename=c:\\Program Files\\Microsoft SQL Server\\MSSQL10.SQLEXPRESS\\MSSQL\\DATA\\UserDB.mdf; Integrated Security=True;Connect Timeout=30;User Instance=True");
cnnUserMan.Open();
//Instantiate and initialize command
cmmUser = new SqlCommand("SelectID", cnnUserMan);
cmmUser.CommandType = System.Data.CommandType.StoredProcedure;
//drdUser = cmmUser.ExecuteReader();
Console.WriteLine(cmmUser.ExecuteReader());
Console.ReadLine();
}
}
}
Thanks.
cmmUser.ExecuteReader() executes the stored procedure and returns a SqlDataReader object. Thus you need to use the SqlDataReader that you commented out like this:
Also I would recommend wrapping the instantiation of your SqlConnection into a using block so that it gets disposed once you are done with it like this:
UPDATE
As per marc_s’s comment, it makes sense to wrap all the disposable components, SqlConnection, SqlCommand, and SqlDataReader in a using block to make sure they are disposed of properly rather than my original solution that ONLY wrapped the SqlConnection with a using block.
UPDATE 2
As per the comment by Thorarin it looks cleaner to declare the variable as part of the using block, especially in this case where you don’t need the variables outside each of the using block.