public Product GetProduct(int ID){ SqlConnection con = new SqlConnection(connectionString); SqlCommand cmd = new SqlCommand("GetProductByID", con); cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@ProductID", ID);
try { con.Open(); SqlDataReader reader = cmd.ExecuteReader(CommandBehavior.SingleRow); if (reader.Read()) { Product product = new Product((string)reader["ProductName"], (decimal)reader["UnitPrice"]); return (product); } else { return null; } } finally { con.Close(); }}
public class Product { public string ProductName { get; set; } public decimal UnitPrice { get; set; }
public Product(string productName, decimal unitPrice) { ProductName = productName; UnitPrice = unitPrice; } }
With its Stored Procedure as such:
USE [Northwind]GO/****** Object: StoredProcedure [dbo].[GetProductByID] Script Date: 07/28/2013 16:18:34 ******/SET ANSI_NULLS ONGOSET QUOTED_IDENTIFIER ONGOALTER PROCEDURE [dbo].[GetProductByID] @ProductID nchar(5)ASSELECT ProductName, UnitPriceFROM Products WHERE ProductID = @ProductID
However, I do not want to depend on the Stored Procedure and want to input in the Query as text, is that possible? When I replace the above code with below, it shows error connecting to database:
public Product GetProduct(int ID){ SqlConnection con = new SqlConnection(connectionString); SqlCommand cmd = new SqlCommand(); cmd.Connection = con; cmd.CommandType = CommandType.Text; cmd.CommandText = "SELECT ProductName, UnitPrice FROM Products WHERE ProductID = @ProductID"; SqlParameter parameter1 = cmd.Parameters.Add("@ProductID", SqlDbType.Int); parameter1.Direction = ParameterDirection.Input; try { con.Open(); SqlDataReader reader = cmd.ExecuteReader(CommandBehavior.SingleRow); if (reader.Read()) { Product product = new Product((string)reader["ProductName"], (decimal)reader["UnitPrice"]); return (product); } else { return null; } } finally { con.Close(); } }
Can anyone points to me where are my mistakes?
thanks.