Executing SQL query from C# code - c#

I'm trying to execute SQL query from C# code, but it doesn't return any values, but when I write query directly to SQL it works fine.
static int TestGettingData()
{
int rows;
string connectionString = System.Configuration.ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;
using (SqlConnection connection = new SqlConnection(connectionString))
{
using (SqlCommand command = new SqlCommand("SELECT [UserName] FROM [aspnet_Users]", connection))
{
connection.Open();
rows = command.ExecuteNonQuery();
}
}
return rows;
}
And connection string:
<connectionStrings>
<add name ="DefaultConnection" connectionString="Server=myServer;
Database=MyDatabase;User
Id=User;
Password=password;
MultipleActiveResultSets=True;"
providerName="System.Data.SqlClient"/>
</connectionStrings>
And TestGettingData() always returning -1.

There are multiple ways to get Data out of your Database
ExecuteScalar
if you have one result field you can use
string Command = "SELECT [UserName] FROM [aspnet_Users];";
using (SqlConnection myConnection = new SqlConnection(ConnectionString))
{
myConnection.Open();
using (SqlCommand myCommand = new SqlCommand(Command, myConnection))
{
string Result = (string)myCommand.ExecuteScalar(); // returns the first column of the first row
}
}
SqlDataAdapter
if you expect multiple rows / columns you can load it into a DataTable by
string Command = "SELECT [UserName] FROM [aspnet_Users]";
using (SqlConnection myConnection = new SqlConnection(ConnectionString))
{
using (SqlDataAdapter myDataAdapter = new SqlDataAdapter(Command, myConnection))
{
DataTable dtResult = new DataTable();
myDataAdapter.Fill(dtResult);
}
}
SqlDataReader
Another solution is the SQLDataReader. E.g. if you want to load all rows of a column into a List. This has less overhead than the DataAdapter.
List<string> Result = new List<string>();
string Command = "SELECT [UserName] FROM [aspnet_Users];";
using (SqlConnection mConnection = new SqlConnection(ConnectionString))
{
mConnection.Open();
using (SqlCommand cmd = new SqlCommand(Command, mConnection))
{
using (SqlDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
Result.Add((string)reader[0]);
}
}
}
}

Because documentation say so;
For UPDATE, INSERT, and DELETE statements, the return value is the
number of rows affected by the command. When a trigger exists on a
table being inserted or updated, the return value includes the number
of rows affected by both the insert or update operation and the number
of rows affected by the trigger or triggers. For all other types of
statements, the return value is -1. If a rollback occurs, the return
value is also -1.
You can use COUNT(*) wiht ExecuteScalar method to get your number.
using (SqlCommand command = new SqlCommand("SELECT COUNT([UserName]) FROM [aspnet_Users]", connection))
{
connection.Open();
rows = (int)command.ExecuteScalar();
}

Here's what I think is the best way to access and retrieve data from a DB:
Create a DBconnection class
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SQLexample
{
/// <summary>
/// A class that makes the connection to the SQL Database
/// </summary>
class DBconnection
{
// variables
private string sql_string;
private string strCon;
System.Data.SqlClient.SqlDataAdapter da_1;
// set methods
public string Sql
{
set { sql_string = value; }
}
public string connection_string
{
set { strCon = value; }
}
// DataSet
public System.Data.DataSet GetConnection
{
get { return MyDataSet(); }
}
// MyDataSet method
private System.Data.DataSet MyDataSet()
{
System.Data.SqlClient.SqlConnection con = new System.Data.SqlClient.SqlConnection(strCon);
con.Open();
da_1 = new System.Data.SqlClient.SqlDataAdapter(sql_string, con);
System.Data.DataSet dat_set = new System.Data.DataSet();
da_1.Fill(dat_set, "Table_Data_1");
con.Close();
return dat_set;
}
// Update DB method
public void UpdateDB(System.Data.DataSet ds)
{
System.Data.SqlClient.SqlCommandBuilder cb = new System.Data.SqlClient.SqlCommandBuilder(da_1);
cb.DataAdapter.Update(ds.Tables[0]);
}
}
}
Then, from your other classes, whenever you want to access DB you do it like this:
try
{
objConnect = new DBconnection();
conStringAUTH = Properties.Settings.Default.authConnectionString;
objConnect.connection_string = conStringAUTH;
objConnect.Sql = "QUERY GOES HERE";
ds = objConnect.GetConnection;
// Data manipulation
maxRows = ds.Tables[0].Rows.Count;
if (maxRows == 0)
{
// Your query returned no values
}
}
catch (Exception err)
{
MessageBox.Show(err.Message);
}
Hope this helps...

Related

The ConnectionString property initialization

Although this question seems like have answers already but my case is different, here's how.
It works the first time but fails for subsequent requests.
I'm creating the connection in the main class and passing to the DB class as a dependency in it's constructor and it's meant to be re-used for each call.
public class DB
{
private SqlConnection conn;
public DB(SqlConnection conn)
{
this.conn = conn;
}
public List<Records> GetRecords()
{
using (conn){
conn.Open();
using (SqlCommand cmd = new SqlCommand("SELECT * FROM Records", conn))
using (SqlDataReader reader = cmd.ExecuteReader())
{
List<Records> rows = new List<Records>();
while (reader.Read())
{
rows.Add(new Records(reader.GetString(1)));
}
return rows;
}
}
}
}
Caller class
string connection = $#"
Data Source=;
Initial Catalog=;
Persist Security Info=True;
User ID={env["DATABASE_USER"]};
Password={env["DATABASE_PASSWORD"]};";
Db db = new DB(new SqlConnection(connection));
db.GetRecords();
fail:
Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware[1]
An unhandled exception has occurred while executing the request. System.InvalidOperationException: The ConnectionString property has
not been initialized.
I'm not 100% sure, but I guess the problem is the
using(conn)
when the using is closed, the SqlConnection will be disposed.
so when you call again db.GetRecords();,
conn.Open() is not initialized. -> exception
You shouldn't use SQLConnection as a field, but as a local variable inside the method. Change your class to take in the connection string inside it's parameter instead of an instance of SqlConnection and initialize it in any method that use it:
public class DB
{
private string connectionString;
public DB(string connectionString)
{
this.connectionString = connectionString;
}
public List<Records> GetRecords()
{
using (var conn = new SqlConnection(connectionString)){
conn.Open();
using (SqlCommand cmd = new SqlCommand("SELECT * FROM Records", conn))
using (SqlDataReader reader = cmd.ExecuteReader())
{
List<Records> rows = new List<Records>();
while (reader.Read())
{
rows.Add(new Records(reader.GetString(1)));
}
return rows;
}
}
}
}
For more details, read this.

Handling Database Connection in C#

I am Creating WinForm application using C# and SqlServer. I have to handle many database CRUD Queries on it. And also there are so many forms and so many controllers.
Now I want to know is, If i create common class for handle database connectivity with many methods for open connection, close connection, execute Sql command or do any other data retrievals. This method is good or bad?
or below method for run every query is good or bad?
using (SqlConnection connection = new SqlConnection("Integrated Security=SSPI;Initial Catalog=MYDB"))
{
connection.Open();
// Pool A is created.
}
which method is better for performance and security?
Here are some points to think about when using a connection.
1) Dispose the connection object as soon as you no longer need it by using the using statement:
using (var conn = new SqlConnection(connectionstring))
{
// your sql magic goes here
}
2) If you're not disposing the object immediately, you can make sure the connection is closed using a try-finally statement:
var conn = new SqlConnection(connectionstring);
try
{
// do sql shizzle
}
finally
{
conn.Close();
}
3) To prevent SQL injection, use parameterized queries, never concatenated strings
using (var conn = new SqlConnection(connectionstring))
{
conn.Open();
using(var comm = new SqlCommand("select * from FooBar where foo = #foo", conn))
{
comm.Parameters.Add(new SqlParameter("#foo", "bar"));
// also possible:
// comm.Parameters.AddWithValue("#foo", "bar");
using(var reader = comm.ExecuteReader())
{
// Do stuff with the reader;
}
}
}
4) If you're performing multiple update, insert or delete statements, and they all need to be succesful at once, use a transaction:
using (var conn = new SqlConnection(connectionstring))
{
conn.Open();
using(var trans = conn.BeginTransaction())
{
try
{
using(var comm = new SqlCommand("delete from FooBar where fooId = #foo", conn, trans))
{
comm.Parameters.Add(new SqlParameter { ParameterName = "#foo", DbType = System.Data.DbType.Int32 });
for(int i = 0; i < 10 ; i++)
{
comm.Parameters["#foo"].Value = i;
comm.ExecuteNonQuery();
}
}
trans.Commit();
}
catch (Exception exe)
{
trans.Rollback();
// do some logging
}
}
}
5) Stored procedures are used similarly:
using (var conn = new SqlConnection(connectionstring))
{
conn.Open();
using (var comm = new SqlCommand("FooBarProcedure", conn) { CommandType = CommandType.StoredProcedure })
{
comm.Parameters.Add(new SqlParameter("#FooBar", "shizzle"));
comm.ExecuteNonQuery();
}
}
(Source stored procedures: this Answer)
Multi threading: The safest way to use multi threading and SQL connections is to always close and dispose your connection object. It's the behavior the SqlConnection was designed for. (Source: Answer John Skeet)
Best practice is make a common DBHelper class and create CRUD methods into that class.
I am adding code snippet.This may help you.
web.config
<connectionStrings>
<add name="mssqltips"
connectionString="data source=localhost;initial catalog=mssqltips;Integrated Security=SSPI;"
providerName="System.Data.SqlClient" />
</connectionStrings>
DBHelper.cs
//Opening Connection
public SqlConnection GetConnection(string connectionName)
{
string cnstr = ConfigurationManager.ConnectionStrings[connectionName].ConnectionString;
SqlConnection cn = new SqlConnection(cnstr);
cn.Open();
return cn;
}
//for select
public DataSet ExecuteQuery(
string connectionName,
string storedProcName,
Dictionary<string, sqlparameter=""> procParameters
)
{
DataSet ds = new DataSet();
using(SqlConnection cn = GetConnection(connectionName))
{
using(SqlCommand cmd = cn.CreateCommand())
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = storedProcName;
// assign parameters passed in to the command
foreach (var procParameter in procParameters)
{
cmd.Parameters.Add(procParameter.Value);
}
using (SqlDataAdapter da = new SqlDataAdapter(cmd))
{
da.Fill(ds);
}
}
}
return ds;
}
//for insert,update,delete
public int ExecuteCommand(
string connectionName,
string storedProcName,
Dictionary<string, SqlParameter> procParameters
)
{
int rc;
using (SqlConnection cn = GetConnection(connectionName))
{
// create a SQL command to execute the stored procedure
using (SqlCommand cmd = cn.CreateCommand())
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = storedProcName;
// assign parameters passed in to the command
foreach (var procParameter in procParameters)
{
cmd.Parameters.Add(procParameter.Value);
}
rc = cmd.ExecuteNonQuery();
}
}
return rc;
}
If you do not want to dispose context every time you can create repository class and inject SqlConnection inside.
using (SqlConnection connection = new SqlConnection("Integrated Security=SSPI;Initial Catalog=MYDB"))
{
repository.SetConnection(connection);
var values = repository.GetSomething();
}
And Create Class:
public Class Repository
{
private SqlConnection _connection {get; set;}
public void SetConnection(SetConnection connection)
{
_connection = connection;
}
public string GetSomething()
{
_connection.Open();
//do stuff with _connection
_connection.Close();
}
}
Anyway I recommend you to read about ORM's (Entity Framework or Dapper) and SQL injection attack.

Retrieve table names

I'm trying to retrieve the names of the table from the local database I'm using.
This the code I've tried but it never goes through the foreach loop:
public void GetColumnNames()
{
SqlConnection con;
SqlDataAdapter adapter = new SqlDataAdapter();
DataSet ds = new DataSet();
con = new SqlConnection(Properties.Settings.Default.AlhusainSoundDBConnectionString);
List<string> colns = new List<string>();
try
{
con.Open();
}
catch (SqlException ex)
{
MessageBox.Show(ex.Message);
}
foreach (DataTable dt in ds.Tables)
{
colns.Add(dt.TableName);
Console.WriteLine(dt.TableName);
}
}
So could anyone please suggest me how to do that correctly
Regards
To get table names you need to use INFORMATION_SCHEMA
USE <your_database_name>
GO
SELECT * FROM INFORMATION_SCHEMA.TABLES
You haven't done anything except open a connection to the database. Your dataset has not been populated with any data. My approach would be to use a SqlCommand object to execute the following SQL Statement and populate a SqlDataReader
SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES
So, the C# code might look something like this:
string sql = "SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES";
using (SqlConnection con = new SqlConnection(Properties.Settings.Default.AlhusainSoundDBConnectionString))
using (SqlCommand cmd = new SqlCommand(sql, con))
{
con.Open();
using (SqlDataReader dr = cmd.ExecuteReader())
{
while (dr.Read())
{
// do something with each table
string tableName= dr["TABLE_NAME"].ToString();
// OR
// string tableName = dr[0].ToString();
// OR
// string tableName = dr.GetString(0);
}
}
}

Set datatables to be equivalent

This is probably a simple question but I am not experienced in C#.
I have 2 datatables, 1 is basically a copy of the other (like a table to review information). To set the values this is what I am doing now:
string attribute1 = "";
string attribute2 = "";
string attribute3 = "";
.....
DataTable result = new DataTable();
using (SqlConnection con = new SqlConnection("user id=user_id;password=pwd;server=serverstring;Trusted_Connection=yes;database=database;connection timeout=30"))
{
using (SqlCommand cmd = new SqlCommand("SELECT * FROM table1 WHERE parameter=#identifying_parameter", con))
{
cmd.Parameters.AddWithValue("#identifying_parameter", "example");
con.Open();
SqlDataReader reader = cmd.ExecuteReader();
if (reader.Read())
{
attribute1 = Convert.ToString(reader["attribute1"]);
attribute2 = Convert.ToString(reader["attribute2"]);
attribute3 = Convert.ToString(reader["attribute3"]);
.....
}
con.Close();
}
}
using (SqlConnection con = new SqlConnection("user id=user_2;password=pwd;server=serverstring;Trusted_Connection=yes;database=database;connection timeout=30"))
{
using (SqlCommand cmd = new SqlCommand("INSERT INTO table2 (attribute1, attribute2, attribute3, ...) VALUES(#attribute1, #attribute2, #attribute3, ...)", con))
{
cmd.Parameters.AddWithValue("#attribute1", attribute1);
cmd.Parameters.AddWithValue("#attribute2", attribute2);
cmd.Parameters.AddWithValue("#attribute3", attribute3);
....
con.Open();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(result);
con.Close();
da.Dispose();
}
}
Obviously I might have a lot of attributes, so is there a simpler way to set every attribute in the table to be equal in C#?
You can use INSERT..INTO..SELECT
DataTable result = new DataTable();
using (SqlConnection con = new SqlConnection("user id=user_2;password=pwd;server=serverstring;Trusted_Connection=yes;database=database;connection timeout=30"))
{
using (SqlCommand cmd = new SqlCommand(#"INSERT INTO table2 (attribute1, attribute2, attribute3, ...)
SELECT attribute1, attribute2, attribute3 ... FROM table1
WHERE parameter=#identifying_parameter
", con))
{
cmd.Parameters.AddWithValue("#identifying_parameter", "example");
con.Open();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(result);
con.Close();
da.Dispose();
}
}
You can use * instead of specifying the column name, although which is not good practice..
In order to make a second Table identical (or "equivalent" as per your definition) to the first one (for certainty let's call it sourceTable), you can use SqlBulkCopy.WriteToServer Method (DataTable)(re: https://msdn.microsoft.com/en-us/library/ex21zs8x%28v=vs.110%29.aspx)
using (SqlConnection YourConnection= new SqlConnection(YourConnectionString))
{
YourConnection.Open();
using (SqlBulkCopy bulkCopy = new SqlBulkCopy(YourConnection))
{
bulkCopy.DestinationTableName = "dbo.YourDestinationTable";
try
{
// Write from the source to the destination.
bulkCopy.WriteToServer(sourceTable);
}
catch (Exception ex) { }
}
}
In order to get a sourceTable you can use the following code snippet:
DataTable sourceTable = SqlReadDB(YourConnString, "SELECT *")
private static DataTable SqlReadDB(string ConnString, string SQL)
{
DataTable _dt;
try
{
using (SqlConnection _connSql = new SqlConnection(ConnString))
{
using (SqlCommand _commandl = new SqlCommand(SQL, _connSql))
{
_commandSql.CommandType = CommandType.Text;
_connSql.Open();
using (SqlCeDataReader _dataReaderSql = _commandSql.ExecuteReader(CommandBehavior.CloseConnection))
{
_dt = new DataTable();
_dt.Load(_dataReaderSqlCe);
_dataReaderSql.Close();
}
}
_connSqlCe.Close();
return _dt;
}
}
catch { return null; }
}
}
Hope this may help.

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