Working with a QueryString and placing value in Stored Procedure? - c#

I am working with ASP.NET and SQL Server 2005.
I know how to create a stored proceudre but i do not know what to place in a stored procedure when i need to make use of a QueryString.
My SQL Statement in CODE =
"SELECT * FROM TableName WHERE ID = '" + Request.QueryString("ID") + "'"
Now what must i place in my stored procedure to get this to work? I want to call a stored procedure and thus do not want to use this code in my code behind.
Thanks in advance!

Create an sqlcommand object
set the commandtext = "StoredProcName"
add an sqlParameter with the name of your sproc parameter - set its type
set its value to Request.QueryString("ID")
check this out for full instructions:
http://support.microsoft.com/kb/306574

Try the following code:
SqlCommand mycommand = new SqlCommand("yourstoredproc", con);
mycommand.CommandType = CommandType.StoredProcedure;
mycommand.Parameters.AddWithValue("#yourparam", Request.QueryString["ID"]);
SqlDataAdapter adapter = new SqlDataAdapter();
adapter.SelectCommand = mycommand;
DataSet dataset = new DataSet();
adapter.Fill(dataset);

SqlCommand cmd = new SqlCommand("storedprocedure_name",con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#parameter_of-procedure",Request.QueryString"ID"]);
SqlDataAdapter adapter = new SqlDataAdapter();
adapter.SelectCommand = mycommand;
DataSet dataset = new DataSet();
adapter.Fill(dataset);
//using sqldatareader
SqlCommand cmd = new SqlCommand("yourstoredproc", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#parameters_of_procedure",Request.QueryString["ID"]);
con.open()
sqldatareader dr=cmd.executereader();
gridview1.datasouce=dr;
gridview1.databind();
con.close();

The answer for this problem is located here

Related

Gridview datasource from database stored procedure

This is the database stored procedure:
ALTER PROCEDURE [dbo].[getShift]
#rfiddata VARCHAR(50)
AS
BEGIN
SELECT
pd.TP, s.s_name, dt.dt_type, dr.dr_date
FROM
TA_System_PersonalDetails pd
INNER JOIN
TA_System_DutyRequest dr ON pd.TP = DR.TP
INNER JOIN
TA_System_Duty d ON dr.d_ID = d.d_ID
INNER JOIN
TA_System_Shift s ON d.s_ID = s.s_ID
INNER JOIN
TA_System_DutyType dt ON d.dt_ID = dt.dt_ID
WHERE
pd.rfid_card = #rfiddata
AND dr.dr_date = CAST(GETDATE() AS DATE)
END
And this the C# code:
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
con.Open();
SqlCommand cmd = new SqlCommand("dbo.getShift", con);
cmd.Parameters.AddWithValue("#rfiddata", data);
cmd.CommandType = CommandType.StoredProcedure;
gvDetails.DataSource = cmd.ExecuteNonQuery();
con.Close();
The gridview still not able to show the value. And this project is in windows form C#. Hence, there is no DataBind() function. Thanks in advance for the help!
I hope this code will help
First we create a connector to connect to the database
string cnStr = #"Persist Security Info=False;User ID=usr;password=pwe; Initial Catalog=theDataBase;Data Source=yourDatasource";
and create a SqlCommand and after set the CommandType to StoredProcedure:
SqlCommand cmd = new SqlCommand();
Then create a SqlConnection and Open Database:
using(SqlConnection con = new SqlConnection(cnStr))
{
con.Open();
cmd.Connection = con;
cmd.CommandText = "dbo.getShift"; // this is the stored procedure to execute
cmd.CommandType = CommandType.StoredProcedure;
}//Connection automatically closes here without the need to call conn.Close()
Then create a dataset to be filled as the datasource for the gridview:
DataSet ds = new DataSet();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(ds);
grdYourGrid.DataSource = ds;
grdYourGrid.DataBind();

Database update error with SQL Server 2012 and C#

I am trying to update my data in a SQL Server database through C#. I am getting updated. But the problem is the data is updated twice.
For example I have 10 (int) in my balance and if I add another 10, it turns to 30.
Any help would be appreciated.
Here is my code:
protected void LoginClick(object sender, EventArgs e)
{
DataTable dr = new DataTable();
string email = txtEmail.Text;
SqlConnection con = new SqlConnection(Ws.Con);
con.Open();
int s = Convert.ToInt32(add.Text);
SqlCommand cmd = new SqlCommand("Update [Order] set Balance=Balance+'" + s + "',Card='" + card.Text + "' where email=#email ", con);
cmd.Parameters.AddWithValue("email", email);
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
sda.Fill(dt);
int i = cmd.ExecuteNonQuery();
con.Close();
}
I would like to rectify few mistakes in your code,
DataTable is not needed to execute the update query, ExecuteNonQuery will do the job
The adapter.Fill and ExecuteNonQuery do the same job here and that's why your updates happening twice
Make use of parameterization while dealing with user inputs to avoid exceptions
For parsing integers use int.TryParse instead for Convert.ToInt32
I think the following code would help you to do the same function in a smarter way:
int currentBalance = 0;
if(int.TryParse(txtAdd.Text, out currentBalance))
{
string querSql = "Update [Order] set Balance = Balance + #balance," +
" Card = #card where email = #email"
using (SqlConnection dbConn = new SqlConnection("connectionString here"))
{
dbConn.Open();
using (SqlCommand sqlCommand = new SqlCommand(querySql, dbConn))
{
sqlCommand.Parameters.Add("#balance", SqlDbType.int).value = currentBalance;
sqlCommand.Parameters.Add("#card", SqlDbType.VarChar).value = card.Text;
sqlCommand.Parameters.Add("#email", SqlDbType.VarChar).value = email;
sqlCommand.ExecuteNonQuery();
}
}
}
Please note: YOu are parsing the balance as an integer value, so I assume the column Balance is an integer field in the database, if not make use of corresponding datatype for the parameter #balance also update the parsing technique
As per the documentation:
SqlDataAdapter(SqlCommand)
Initializes a new instance of the SqlDataAdapter class with the specified SqlCommand as the SelectCommand property.
What is going wrong in your code?
Actually you are passing SqlDataAdapter your update query as the Select command. So now when you will use this instance of SqlDataAdapter to Fill your datatable then actually you are executing your Update command. Look at the following code along with comments to see what is going wrong:
DataTable dr = new DataTable();
string email = txtEmail.Text;
SqlConnection con = new SqlConnection(Ws.Con);
con.Open();
int s = Convert.ToInt32(add.Text);
SqlCommand cmd = new SqlCommand("Update [Order] set Balance=Balance+'" + s + "',Card='" + card.Text + "' where email=#email ", con);
cmd.Parameters.AddWithValue("email", email);
SqlDataAdapter sda = new SqlDataAdapter(cmd);//The Select command for SqlDataAdapter
//is actually now the update command specified by cmd instnace of SqlCommand
DataTable dt = new DataTable();
sda.Fill(dt);//here SqlDataAdapter will execute it's Select command which is actually set
//to an update statement so your record will be updated
int i = cmd.ExecuteNonQuery();//and here again the update command is being executed now
//directly using the SqlCommand cmd instance and thus your record gets updated twice
con.Close();
Fixed Code:
DataTable dr = new DataTable();
string email = txtEmail.Text;
SqlConnection con = new SqlConnection(Ws.Con);
con.Open();
int s = Convert.ToInt32(add.Text);
SqlCommand cmd = new SqlCommand("Update [Order] set Balance=Balance+'" + s + "',Card='" + card.Text + "' where email=#email ", con);
cmd.Parameters.AddWithValue("email", email);
//Create a new SqlComamnd
SqlCommand selectCommand = new SqlCommand("Select * from [Order]");
//Put the newly created instance as SelectCommand for your SqlDataAdapter
SqlDataAdapter sda = new SqlDataAdapter(selectCommand);
DataTable dt = new DataTable();
sda.Fill(dt);
int i = cmd.ExecuteNonQuery();
con.Close();
Hope this help and do have a look at the documentation for better understanding of the SqlDataAdapter and DataTable. Thanks.

C# chart control populate with stored procedure with parameters

enter image description hereI can populate chart control in C# Winforms with stored procedures without parameters and that's fine. But now I need to use stored procedure with parameters. Any advice how to do that?
Below is my code how i am populating chart control with stored procedure without parameters.
sqlCon.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = sqlCon;
cmd.CommandType = CommandType.StoredProcedure;
SqlDataAdapter myCommand = new SqlDataAdapter("[Proc1]", sqlCon);
DataSet ds = new DataSet();
myCommand.Fill(ds);
DataView source = new DataView(ds.Tables[0]);
chart1.DataSource = source;
chart1.ChartAreas["ChartArea1"].AxisX.Interval = 1;
chart1.Series[0].XValueMember = "Pojazd";
chart1.Series[0].YValueMembers = "Suma";
chart1.DataBind();
Please help me :-)
Just a further explanation of what #Rakitić said.
SqlCommand cmd = new SqlCommand();
cmd.Parameters.Add("#PARAMNAME", SqlDbType.VarChar,10).Value = paramValue;
Then you'll need to add this parameter within your stored procedure. Which I'm just guessing you're using Sql Server:
#PARAMNAME varchar(10)

How to use DataAdapter to call a stored procedure in C# with variable parameters

I am calling the following code in C# to fill a dataAdapter with a given stored procedure "sp1_name". The problem is that I want to call different stored procedures with different parameters. (All SP's do a SELECT)
Let's suppose that my stored procedure name is "SP_SOMESP", then everything works fine.
Let's suppose that my stored procedure name is "SP_SOMESP #Month= 10, #Year = 2010", then it doesn't work. It throws an exception that cannot find this stored procedure.
Any solutions?
Thanks!
//First Connection - SP1
using (SqlConnection con = new SqlConnection(conStr))
{
using (SqlCommand cmd = new SqlCommand(sp1_name, con)) //sp1_name = NAME + PARAMETERS
{
cmd.CommandTimeout = 3600;
cmd.CommandType = CommandType.StoredProcedure;
using (SqlDataAdapter dataAdapter = new SqlDataAdapter(cmd))
{
dataAdapter.Fill(results2);
}
}
}
First Issue:
Parameters in a stored procedure shouldn't be included along with its name
Second Issue:
Having a space in names of stored procedure isn't a good practice.
And for code behind
using(SqlConnection con = new SqlConnection("Your Connection String Here"))
{
SqlCommand cmd = new SqlCommand("sp_SomeName", con);
cmd.CommandType = CommandType.StoredProcedure;
//the 2 codes after this comment is where you assign value to the parameters you
//have on your stored procedure from SQL
cmd.Parameters.Add("#MONTH", SqlDbType.VarChar).Value = "someValue";
cmd.Parameters.Add("#YEAR", SqlDbType.VarChar).Value = "SomeYear";
SqlDataAdapter da = new SqlDataAdapter(cmd);
SqlDataSet ds = new SqlDataSet();
da.Fill(ds); //this is where you put values you get from the Select command to a
//dataset named ds, reason for this is for you to fetch the value from DB to code behind
foreach(DataRow dr in ds.Tables[0].Rows) // this is where you run through the dataset and get values you want from it.
{
someTextBox.Text = dr["Month"].ToString(); //you should probably know this code
}
}
You have to add in the parameters programmatically, see SqlCommand.Parameters.
It would be something like
cmd.Parameters.AddWithValue("#Month", 10);
cmd.Parameters.AddWithValue("#Year", 2010);
This would be after the command is declared and before it is executed.
If you find that you need to delcare the data type, then try it this way
cmd.Parameters.Add("#Month", SqlDbType.Int).Value = 10;
Check this,
using (SQLCommand cmd = new SQLCommand())
{
cmd.CommandText = "SP_SOMESP";
cmd.Parameters.Add("#Month", 10);
cmd.Parameters.Add("#Year", 2010);
cmd.CommandTimeout = 3600;
cmd.CommandType = CommandType.StoredProcedure;
cmd.Connection = con;
}
using (SqlDataAdapter dataAdapter = new SqlDataAdapter(cmd))
{
dataAdapter.SelectCommand = cmd;
dataAdapter.Fill(results2);
}

C# and SQL Server: How do I get values from my SQL Table, by calling my stored procedure with C#?

I created the following stored procedure
CREATE PROCEDURE dbo.GetPoint
AS
SELECT point FROM tLocalGeo
Now I need execute that procedure from my C# Controller and save the data on a list.
As you can see the context of the problem is to get points so then I can display them on google map using javascript for that.
Can you give me some reference how to do it? Do I need SQLReader?
Thank you for your attention.
You can use SqlDataAdapter and DataSet and then can get values from dataset's first table.
SqlCommand cmd = new SqlCommand("store procedure Name", con);
cmd.CommandType = CommandType.StoredProcedure;
SqlDataAdapter adapter= new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
adapter.Fill(ds);
if(ds.Tables[0]!=null && ds.Tables[0].Rows.Count > 0)
{
//your code
}
Hope it helps.
String strConnString = ConfigurationManager.ConnectionStrings["conString"].ConnectionString;
SqlConnection con = new SqlConnection(strConnString);
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "GetPoint";
cmd.Parameters.AddWithValue("#EmployeeID", Empid) // ur input parameter//
cmd.Connection = con;
try
{
con.Open();
GridView1.EmptyDataText = "No Records Found";
GridView1.DataSource = cmd.ExecuteReader() ;
GridView1.DataBind();
}

Categories