Would executing the SqlCommand be completely moot/redundant, and slow things down? - c#

Thanks to some tips and reminders here, I changed my code from this kludgy mess:
try
{
DataSet dsUsage = new DataSet();
SqlConnection conn = new SqlConnection("SERVER=PROSQL05;DATABASE=platypusdata;UID=duckbill;PWD=poisonToe42;Connection Timeout=0");
SqlDataAdapter da = new SqlDataAdapter();
SqlCommand cmd = conn.CreateCommand();
cmd.CommandText = String.Format("Exec sp_ViewProductUsage_MappingRS '{0}', '{1}', '{2}'", mammal, dateBegin, dateEnd);
da.SelectCommand = cmd;
conn.Open();
da.Fill(dsUsage);
conn.Close();
DataTable dtUsage = dsUsage.Tables[0];
if (dtUsage.Rows.Count > 0)
{
foreach (DataRow productUsageByMonthDataRow in dtUsage.Rows)
{
. . .
...to this:
try
{
SqlDataAdapter da = new SqlDataAdapter();
DataSet dsUsage = new DataSet();
using (SqlConnection conn = new SqlConnection(UsageRptConstsAndUtils.PlatypusConnStr))
{
using (SqlCommand cmd = new SqlCommand("sp_ViewProductUsage_MappingRS", conn))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#Unit", SqlDbType.VarChar).Value = _unit;
cmd.Parameters.Add("#BegDate", SqlDbType.DateTime).Value = dtBegin;
cmd.Parameters.Add("#EndDate", SqlDbType.DateTime).Value = dtEnd;
da.SelectCommand = cmd;
conn.Open();
//cmd.ExecuteReader(); <- Is this even necessary?
da.Fill(dsUsage);
}
}
DataTable dtUsage = dsUsage.Tables[0];
if (dtUsage.Rows.Count > 0)
{
// Populate the cells
foreach (DataRow productUsageByMonthDataRow in dtUsage.Rows)
{
. . .
Note that I have SqlCommand's ExecuteReader commented out in the new code because it seems unnecessary due to the SqlDataAdapter being provided the SqlCommand. It works fine. So: am I correct in assuming I can remove cmd.ExecuteReader() altogether? Is there any benefit in retaining it, or would that be totally redundant and create "busy work" for the process?
UPDATE
So, to pass an array of SqlParameter (to the ExecuteDataSet method in MethodMan's answer), I take it that I would first have to do something like:
SqlParameter sqlp = new SqlParameter();
sqlp.ParameterName = "Unit";
sqlp.Value = _unit;
cmd.Parameters.Add(sqlp);
...etc. (and then add them to an array - or, possibly better a generic list of SqlParameter).
UPDATE 2
I just ran into this for the first time: if you use MethodMan's example (which I do) and you use a parameterless query, you need to bypass the parameter-adding loop like so:
if (null != parameters)
{
foreach (var item in parameters)
{
cmd.Parameters.Add(item);
}
}

I would personally create a SqlDBHelper class and pass call the stored procedure using a method such as this
public static class SqlDBHelper
{
public static DataSet ExecuteDataSet(string sql, CommandType cmdType, params SqlParameter[] parameters)
{
using (DataSet ds = new DataSet())
using (SqlConnection connStr = new SqlConnection(ConfigurationManager.ConnectionStrings["DbConn"].ConnectionString))
using (SqlCommand cmd = new SqlCommand(sql, connStr))
{
cmd.CommandType = cmdType;
foreach (var item in parameters)
{
cmd.Parameters.Add(item);
}
try
{
cmd.Connection.Open();
new SqlDataAdapter(cmd).Fill(ds);
}
catch (SqlException ex)
{
//log to a file or write to Console for example
Console.WriteLine(ex.Message);
}
return ds;
}
}
}
If you want to return a DataTable then change the return type in the Method signature and call the following in the return statement below
public static DataTable ExecuteDataSet(string sql, CommandType cmdType, params SqlParameter[] parameters)
return ds.Tables[0];
Here is an example on how you would call the method
someDataTable = SqlDBHelper.ExecuteDataSet("sp_ViewProductUsage_MappingRS", CommandType.StoredProcedure,
new SqlParameter() { ParameterName = "#Unit", SqlDbType = SqlDbType.VarChar, Value = _unit },
new SqlParameter() { ParameterName = "#BegDate", SqlDbType = SqlDbType.DateTime, Value = dtBegin },
new SqlParameter() { ParameterName = "#EndDate", SqlDbType = SqlDbType.DateTime, Value = dtEnd }
);

Related

SqlDataAdapter filling with DataTable does not work

I have this code running in form_load event:
using (SqlConnection sqlConn = new SqlConnection(strConn))
{
sqlConn.Open();
SqlDataAdapter sqlDa = new SqlDataAdapter("pp_sp_MachineAndOp", sqlConn);
DataTable sqlDt = Helper.ExecuteDataTable("pp_sp_MachineAndOp", new SqlParameter("#MachineAndOpID", 7));
sqlDa.Fill(sqlDt);
dgvMachineAndOp.AutoGenerateColumns = false;
dgvMachineAndOp.DataSource = sqlDt;
sqlDa.Dispose();
sqlConn.Close();
}
I get error 'Procedure or function 'pp_sp_MachineAndOp' expects parameter '#MachineAndOpID', which was not supplied.' at line:
sqlDa.Fill(sqlDt);
Important to say that if I open DataTable Visualizer of sqlDt at runtime I see expected results!
Here is a code behind Helper.ExecuteDataTable:
public static DataTable ExecuteDataTable(string storedProcedureName, params SqlParameter[] arrParam)
{
DataTable dt = new DataTable();
// Open the connection
using (SqlConnection sqlConn = new SqlConnection(strConn))
{
try
{
sqlConn.Open();
// Define the command
using (SqlCommand sqlCmd = new SqlCommand())
{
sqlCmd.Connection = sqlConn;
sqlCmd.CommandType = CommandType.StoredProcedure;
sqlCmd.CommandText = storedProcedureName;
// Handle the parameters
if (arrParam != null)
{
foreach (SqlParameter param in arrParam)
{
sqlCmd.Parameters.Add(param);
}
}
// Define the data adapter and fill the dataset
using (SqlDataAdapter da = new SqlDataAdapter(sqlCmd))
{
da.Fill(dt);
}
}
}
catch (SqlException ex)
{
MessageBox.Show(ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
return dt;
}
What I am missing?
Remove everything except
DataTable sqlDt = Helper.ExecuteDataTable("pp_sp_MachineAndOp", new SqlParameter("#MachineAndOpID", 7));
dgvMachineAndOp.AutoGenerateColumns = false;
dgvMachineAndOp.DataSource = sqlDt;
your Helper.ExecuteDataTable is doing everything. you don't need to replicate same this in your code.
I think your helper class is creating connection with database as your data table has data.
So, try to remove stored proc name and connection object from adaptor and then check.
SqlDataAdapter sqlDa = new SqlDataAdapter();//use this only.
you can use below function(modification required as per your need):
public IDataReader ExecuteReader(string spName, object[] parameterValues)
{
command = GetCommand();
command.CommandType = CommandType.StoredProcedure;
command.CommandText = spName;
if (parameterValues != null)
{
for (int i = 0; i < parameterValues.Length; i++)
{
command.Parameters.Add(parameterValues[i]);
}
}
reader = command.ExecuteReader();
if (parameterValues != null)
command.Parameters.Clear();
return reader;
}

Add new parameters to exec procedure

I have a custom SQL exec to execute stored procedure and send DataTable and execute TableType in sql like:
//Execute
db.ExeSQLParam("usp_TaskStatus_Time_Calculation_Final", parameters, "#GuidIdTableType");
ExeSQLParam method:
public bool ExeSQLParam(string SprocName, DataTable paramArray, string tableTypeName)
{
var testc = new SqlParameter();
bool bFlag = false;
SqlCommand cmd = new SqlCommand(SprocName, this.dbconn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(new SqlParameter(tableTypeName, SqlDbType.Structured));
cmd.Parameters[tableTypeName].Value = paramArray;
try
{
cmd.ExecuteNonQuery();
bFlag = true;
}
catch (SqlException e)
{
this.HandleSQLError(e, SprocName, paramArray.ToString());
}
finally
{
cmd.Dispose();
}
return bFlag;
}
My question is how can I add to this method another normal parameters , so I can execute as:
db.ExeSQLParam("usp_TaskStatus_Time_Calculation_Final", parameters, "#GuidIdTableType",
#anoteherParameter = 'valueanotherparameter', #other = 'valueoter');
How can I achieve that?
I try to change it to received output data as DataTable like:
public DataTable ExeSQLParamAndType(string SprocName, DataTable paramArray, string tableTypeName)
{
SqlCommand cmd = new SqlCommand(SprocName, this.dbconn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(new SqlParameter(tableTypeName, SqlDbType.Structured));
cmd.Parameters[tableTypeName].Value = paramArray;
DataTable tbl = new DataTable("Table1")
{
Locale = System.Globalization.CultureInfo.InvariantCulture
};
SqlDataAdapter da = new SqlDataAdapter(cmd);
try
{
da.Fill(tbl);
}
catch (SqlException e)
{
this.HandleSQLError(e, "GetTableBySQL", SprocName);
}
finally
{
cmd.Dispose();
}
return tbl;
}
but where I can add new parameters? with another parameters.Add? I'm a litte confused there
In C# you can provide optional parameters using the 'params' keyword, so you simply rewrite your method and supply the params parametres.

Trying to pass SqlCommand in SqlDataAdapter as parameters

I've successfully built up my method to execute a select command. It is working fine. Then I change my code for SqlDataAdapter DA = new SqlDataAdapter();
I tried to pass SqlCommand as CommandType.Text in the parameters but I can not do it successfully. I get error. Is there any way if I can pass it as parameters. Please see my code.
Running code (aspx page code)
if ((!string.IsNullOrEmpty(user_login.Value)) && (!string.IsNullOrEmpty(user_pass.Value)))
{
// username & password logic
DataTable dt = new DataTable();
string strQuery = "SELECT 1 FROM TBL_USER_INFO WHERE USERNAME = #USERNAME AND PASSWORD = #PASSWORD";
SqlCommand cmd = new SqlCommand(strQuery);
cmd.Parameters.Add("#USERNAME", SqlDbType.VarChar).Value = user_login.Value.Trim();
cmd.Parameters.Add("#PASSWORD", SqlDbType.VarChar).Value = user_pass.Value.Trim();
DBConnection conn_ = new DBConnection();
dt = conn_.SelectData(cmd);
if (conn_.SQL_dt.Rows.Count > 0)
{
Response.Redirect("Home.aspx", false);
}
}
Successful connection class code
public DataTable SelectData(SqlCommand command)
{
try
{
conn.Open();
SqlDataAdapter DA = new SqlDataAdapter();
command.CommandType = CommandType.Text;
command.Connection = conn;
DA.SelectCommand = command;
DA.Fill(SQL_dt);
return SQL_dt;
}
catch (Exception ex)
{
return null;
}
finally
{
conn.Close();
}
}
How can I pass CommandType.Text as parameters for SqlDataAdapter?
Error code
public DataTable SelectData(SqlCommand command)
{
try
{
conn.Open();
SqlDataAdapter DA = new SqlDataAdapter(command.CommandType.ToString(), conn);
// command.CommandType = CommandType.Text;
// command.Connection = conn;
DA.SelectCommand = command;
DA.Fill(SQL_dt);
return SQL_dt;
}
catch (Exception ex)
{
return null;
}
finally
{
conn.Close();
}
}
I am getting this error:
System.InvalidOperationException: Fill: SelectCommand.Connection property has not been initialized.
at System.Data.Common.DbDataAdapter.GetConnection3(DbDataAdapter adapter, IDbCommand command, String method)...
public DataTable SelectData(string query)
{
DataTable dt = new DataTable();
using (SqlConnection con = new SqlConnection("Your Connection String here"))
{
con.Open();
using (SqlCommand cmd = con.CreateCommand())
{
cmd.CommandText = query;
cmd.CommandType = CommandType.Text;
using (SqlDataAdapter adp = new SqlDataAdapter(cmd))
{
adp.Fill(dt);
return dt;
}
}
}
}
To use:
SelectData("select * from yourTable");
Reds has the answer. Just to clean the code up a little bit...
public DataTable SelectData(string query)
{
using (var connection = new SqlConnection("myConnectionString"))
using (var command = new SqlCommand(query, connection))
using (var adapter = new SqlDataAdapter(command))
{
var dt = new DataTable();
connection.Open();
adapter.Fill(dt);
return dt;
}
}
Actually you should pass the connection object on SQLCommand.Hope it helped you
DBConnection conn_ = new DBConnection();
SqlCommand cmd = new SqlCommand(strQuery,conn_);
The error that you are getting is not related to CommandType.Text, it says you have initialised the connection property of of SelectCommand. Basically you should uncomment "command.Connection = conn;" to get rid of this error. If you still face any other issue , it is better to provide those details in the questions to provide accurate answer.

Call non static method from Static method and Bind GridView

Hi My Static Method is
[WebMethod(EnableSession = true)]
public static List<Entity.Report> ChartNavigation(string type, string user, string date)
{
WebForm2 objForm = new WebForm2();
objForm.BindCVTrackerForNavigation(user, date);
List<Entity.Report> listchart = new List<Entity.Report>();
using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["Recruitment"].ConnectionString))
{
string sqlString = "GetNumberOfCVSentForChartNavigation";
using (SqlCommand cmd = new SqlCommand(sqlString, conn))
{
cmd.CommandType = System.Data.CommandType.StoredProcedure;
cmd.Parameters.Add(new SqlParameter("#UserName", user.Replace("\"", "")));
cmd.Parameters.Add(new SqlParameter("#Date", date.Replace("\"", "")));
conn.Open();
SqlDataReader rdr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
while (rdr.Read())
{
Entity.Report obj = new Entity.Report();
Utilities.Common.Fill(obj, rdr);
listchart.Add(obj);
}
conn.Close();
}
}
return listchart;
}
And I am calling Non static method from it. My non static method is
protected void BindCVTrackerForNavigation(string User,string Date)
{
DataSet ds = new DataSet();
using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["Recruitment"].ConnectionString))
{
string sqlString = "GetNumberOfCVSentForNavigation";
using (SqlCommand cmd = new SqlCommand(sqlString, conn))
{
cmd.CommandType = System.Data.CommandType.StoredProcedure;
cmd.Parameters.Add(new SqlParameter("#UserName", User.Replace("\"", "")));
cmd.Parameters.Add(new SqlParameter("#Date", Date.Replace("\"", "")));
conn.Open();
SqlDataAdapter DA1 = new SqlDataAdapter(cmd);
DA1.Fill(ds);
conn.Close();
}
if (ds.Tables.Count > 0)
{
if (ds.Tables[0].Rows.Count > 0)
{
gvCVTracker.DataSource = ds.Tables[0];
gvCVTracker.DataBind();
}
}
}
}
When datasource is apply to gvCVTracker it throws error Object reference not set to an instance of an object. I dont know what is the problem? Any help would be appriciated.Thanks.
You must use Page.LoadControl to create an instance of the WebForm2 for it to also process the initialization of the controls.

How to execute a stored procedure within C# program

I want to execute this stored procedure from a C# program.
I have written the following stored procedure in a SqlServer query window and saved it as
stored1:
use master
go
create procedure dbo.test as
DECLARE #command as varchar(1000), #i int
SET #i = 0
WHILE #i < 5
BEGIN
Print 'I VALUE ' +CONVERT(varchar(20),#i)
EXEC(#command)
SET #i = #i + 1
END
EDITED:
using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Data.SqlClient;
namespace AutomationApp
{
class Program
{
public void RunStoredProc()
{
SqlConnection conn = null;
SqlDataReader rdr = null;
Console.WriteLine("\nTop 10 Most Expensive Products:\n");
try
{
conn = new SqlConnection("Server=(local);DataBase=master;Integrated Security=SSPI");
conn.Open();
SqlCommand cmd = new SqlCommand("dbo.test", conn);
cmd.CommandType = CommandType.StoredProcedure;
rdr = cmd.ExecuteReader();
/*while (rdr.Read())
{
Console.WriteLine(
"Product: {0,-25} Price: ${1,6:####.00}",
rdr["TenMostExpensiveProducts"],
rdr["UnitPrice"]);
}*/
}
finally
{
if (conn != null)
{
conn.Close();
}
if (rdr != null)
{
rdr.Close();
}
}
}
static void Main(string[] args)
{
Console.WriteLine("Hello World");
Program p= new Program();
p.RunStoredProc();
Console.Read();
}
}
}
This displays the exception Cannot find the stored procedure dbo.test. Do I need to provide the path? If yes, in which location should the stored procedures be stored?
using (var conn = new SqlConnection(connectionString))
using (var command = new SqlCommand("ProcedureName", conn) {
CommandType = CommandType.StoredProcedure }) {
conn.Open();
command.ExecuteNonQuery();
}
using (SqlConnection conn = new SqlConnection("Server=(local);DataBase=Northwind;Integrated Security=SSPI")) {
conn.Open();
// 1. create a command object identifying the stored procedure
SqlCommand cmd = new SqlCommand("CustOrderHist", conn);
// 2. set the command object so it knows to execute a stored procedure
cmd.CommandType = CommandType.StoredProcedure;
// 3. add parameter to command, which will be passed to the stored procedure
cmd.Parameters.Add(new SqlParameter("#CustomerID", custId));
// execute the command
using (SqlDataReader rdr = cmd.ExecuteReader()) {
// iterate through results, printing each to console
while (rdr.Read())
{
Console.WriteLine("Product: {0,-35} Total: {1,2}",rdr["ProductName"],rdr["Total"]);
}
}
}
Here are some interesting links you could read:
http://www.csharp-station.com/Tutorials/AdoDotNet/Lesson07.aspx
http://www.c-sharpcorner.com/UploadFile/dclark/InsOutsinCS11302005072332AM/InsOutsinCS.aspx
http://www.codeproject.com/KB/cs/simplecodeasp.aspx
http://msdn.microsoft.com/en-us/library/ms171921(VS.80).aspx
Calling stored procedure in C#:
SqlCommand cmd = new SqlCommand("StoredProcedureName",con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#value",txtValue.Text);
con.Open();
int rowAffected = cmd.ExecuteNonQuery();
con.Close();
using (SqlConnection sqlConnection1 = new SqlConnection("Your Connection String")) {
using (SqlCommand cmd = new SqlCommand()) {
Int32 rowsAffected;
cmd.CommandText = "StoredProcedureName";
cmd.CommandType = CommandType.StoredProcedure;
cmd.Connection = sqlConnection1;
sqlConnection1.Open();
rowsAffected = cmd.ExecuteNonQuery();
}}
This is code for executing stored procedures with and with out parameters via reflection.
Do note that the objects property names need to match the parameters of the stored procedure.
private static string ConnString = ConfigurationManager.ConnectionStrings["SqlConnection"].ConnectionString;
private SqlConnection Conn = new SqlConnection(ConnString);
public void ExecuteStoredProcedure(string procedureName)
{
SqlConnection sqlConnObj = new SqlConnection(ConnString);
SqlCommand sqlCmd = new SqlCommand(procedureName, sqlConnObj);
sqlCmd.CommandType = CommandType.StoredProcedure;
sqlConnObj.Open();
sqlCmd.ExecuteNonQuery();
sqlConnObj.Close();
}
public void ExecuteStoredProcedure(string procedureName, object model)
{
var parameters = GenerateSQLParameters(model);
SqlConnection sqlConnObj = new SqlConnection(ConnString);
SqlCommand sqlCmd = new SqlCommand(procedureName, sqlConnObj);
sqlCmd.CommandType = CommandType.StoredProcedure;
foreach (var param in parameters)
{
sqlCmd.Parameters.Add(param);
}
sqlConnObj.Open();
sqlCmd.ExecuteNonQuery();
sqlConnObj.Close();
}
private List<SqlParameter> GenerateSQLParameters(object model)
{
var paramList = new List<SqlParameter>();
Type modelType = model.GetType();
var properties = modelType.GetProperties();
foreach (var property in properties)
{
if (property.GetValue(model) == null)
{
paramList.Add(new SqlParameter(property.Name, DBNull.Value));
}
else
{
paramList.Add(new SqlParameter(property.Name, property.GetValue(model)));
}
}
return paramList;
}
SqlConnection conn = null;
SqlDataReader rdr = null;
conn = new SqlConnection("Server=(local);DataBase=Northwind;Integrated Security=SSPI");
conn.Open();
// 1. create a command object identifying
// the stored procedure
SqlCommand cmd = new SqlCommand("CustOrderHist", conn);
// 2. set the command object so it knows
// to execute a stored procedure
cmd.CommandType = CommandType.StoredProcedure;
// 3. add parameter to command, which
// will be passed to the stored procedure
cmd.Parameters.Add(new SqlParameter("#CustomerID", custId));
// execute the command
rdr = cmd.ExecuteReader();
// iterate through results, printing each to console
while (rdr.Read())
{
Console.WriteLine("Product: {0,-35} Total: {1,2}", rdr["ProductName"], rdr["Total"]);
}
By using Ado.net
using System;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
namespace PBDataAccess
{
public class AddContact
{
// for preparing connection to sql server database
private SqlConnection conn;
// for preparing sql statement or stored procedure that
// we want to execute on database server
private SqlCommand cmd;
// used for storing the result in datatable, basically
// dataset is collection of datatable
private DataSet ds;
// datatable just for storing single table
private DataTable dt;
// data adapter we use it to manage the flow of data
// from sql server to dataset and after fill the data
// inside dataset using fill() method
private SqlDataAdapter da;
// created a method, which will return the dataset
public DataSet GetAllContactType()
{
// retrieving the connection string from web.config, which will
// tell where our database is located and on which database we want
// to perform opearation, in this case we are working on stored
// procedure so you might have created it somewhere in your database.
// connection string will include the name of the datasource, your
// database name, user name and password.
using (conn = new SqlConnection(ConfigurationManager.ConnectionString["conn"]
.ConnectionString))
{
// Addcontact is the name of the stored procedure
using (cmd = new SqlCommand("Addcontact", conn))
{
cmd.CommandType = CommandType.StoredProcedure;
// here we are passing the parameters that
// Addcontact stored procedure expect.
cmd.Parameters.Add("#CommandType",
SqlDbType.VarChar, 50).Value = "GetAllContactType";
// here created the instance of SqlDataAdapter
// class and passed cmd object in it
da = new SqlDataAdapter(cmd);
// created the dataset object
ds = new DataSet();
// fill the dataset and your result will be
stored in dataset
da.Fill(ds);
}
}
return ds;
}
}
****** Stored Procedure ******
CREATE PROCEDURE Addcontact
#CommandType VARCHAR(MAX) = NULL
AS
BEGIN
IF (#CommandType = 'GetAllContactType')
BEGIN
SELECT * FROM Contacts
END
END
this is an example of a stored procedure that returns a value and it's execution in c#
CREATE PROCEDURE [dbo].[InsertPerson]
-- Add the parameters for the stored procedure here
#FirstName nvarchar(50),#LastName nvarchar(50),
#PersonID int output
AS
BEGIN
insert [dbo].[Person](LastName,FirstName) Values(#LastName,#FirstName)
set #PersonID=SCOPE_IDENTITY()
END
Go
--------------
// Using stored procedure in adapter to insert new rows and update the identity value.
static void InsertPersonInAdapter(String connectionString, String firstName, String lastName) {
String commandText = "dbo.InsertPerson";
using (SqlConnection conn = new SqlConnection(connectionString)) {
SqlDataAdapter mySchool = new SqlDataAdapter("Select PersonID,FirstName,LastName from [dbo].[Person]", conn);
mySchool.InsertCommand = new SqlCommand(commandText, conn);
mySchool.InsertCommand.CommandType = CommandType.StoredProcedure;
mySchool.InsertCommand.Parameters.Add(
new SqlParameter("#FirstName", SqlDbType.NVarChar, 50, "FirstName"));
mySchool.InsertCommand.Parameters.Add(
new SqlParameter("#LastName", SqlDbType.NVarChar, 50, "LastName"));
SqlParameter personId = mySchool.InsertCommand.Parameters.Add(new SqlParameter("#PersonID", SqlDbType.Int, 0, "PersonID"));
personId.Direction = ParameterDirection.Output;
DataTable persons = new DataTable();
mySchool.Fill(persons);
DataRow newPerson = persons.NewRow();
newPerson["FirstName"] = firstName;
newPerson["LastName"] = lastName;
persons.Rows.Add(newPerson);
mySchool.Update(persons);
Console.WriteLine("Show all persons:");
ShowDataTable(persons, 14);
Using Dapper. so i added this i hope anyone help.
public void Insert(ProductName obj)
{
SqlConnection connection = new SqlConnection(Connection.GetConnectionString());
connection.Open();
connection.Execute("ProductName_sp", new
{ #Name = obj.Name, #Code = obj.Code, #CategoryId = obj.CategoryId, #CompanyId = obj.CompanyId, #ReorderLebel = obj.ReorderLebel, #logo = obj.logo,#Status=obj.Status, #ProductPrice = obj.ProductPrice,
#SellingPrice = obj.SellingPrice, #VatPercent = obj.VatPercent, #Description=obj.Description, #ColourId = obj.ColourId, #SizeId = obj.SizeId,
#BrandId = obj.BrandId, #DisCountPercent = obj.DisCountPercent, #CreateById =obj.CreateById, #StatementType = "Create" }, commandType: CommandType.StoredProcedure);
connection.Close();
}
No Dapper answer here. So I added one
using Dapper;
using System.Data.SqlClient;
using (var cn = new SqlConnection(#"Server=(local);DataBase=master;Integrated Security=SSPI"))
cn.Execute("dbo.test", commandType: CommandType.StoredProcedure);
Please check out Crane (I'm the author)
https://www.nuget.org/packages/Crane/
SqlServerAccess sqlAccess = new SqlServerAccess("your connection string");
var result = sqlAccess.Command().ExecuteNonQuery("StoredProcedureName");
Also has a bunch of other features you might like.
You mean that your code is DDL?
If so, MSSQL has no difference. Above examples well shows how to invoke this. Just ensure
CommandType = CommandType.Text
Most Simple and straight forward..
SqlCommand cmd = new SqlCommand("StoredProcedureName",con); // Just like you declared it
cmd.CommandType = CommandType.StoredProcedure; // an attribute related to the object
cmd.Parameters.AddWithValue("#value",txtValue.Text); // Parameter name and text source
con.Open();
int rowAffected = cmd.ExecuteNonQuery();
con.Close();
What I made, in my case I wanted to show procedure's result in dataGridView:
using (var command = new SqlCommand("ProcedureNameHere", connection) {
// Set command type and add Parameters
CommandType = CommandType.StoredProcedure,
Parameters = { new SqlParameter("#parameterName",parameterValue) }
})
{
// Execute command in Adapter and store to dataset
var adapter = new SqlDataAdapter(command);
var dataset = new DataSet();
adapter.Fill(dataset);
// Display results in DatagridView
dataGridView1.DataSource = dataset.Tables[0];
}

Categories

Resources