Stored procedure not working - asp.net

I have trouble converting this to stored procedure
//The string included in the sql statement:
string employer = Session["Employer"].ToString();
then the sql statement
update tblWorkData set EmployerName='"+txtemployername.text+"' where EmployerName='"+Employer+"' //the string above
This works fine in asp.net
But when I turn it into stored procedure,
create proc updateWork
#EmployerName nvarchar(max)
as
begin
update tblWorkData set EmployerName=#EmployerName where EmployerName=#EmployerName
end
Now when I execute the sp on asp.net,
string update = "updateWork '"+employer+"','"+txtemployername.text+"'";
I got an error saying "too many arguements". What should I do?

Your stored procedure only takes one argument and you're calling it with two. To fix this you need to alter the procedure to take two arguments like this:
create proc updateWork
#EmployerName nvarchar(max),
#Employer nvarchar(max)
as
begin
update tblWorkData set EmployerName=#EmployerName where EmployerName=#Employer
end
I changed the whereclause as I guess you meant it to be. As it was before it didn't actually do anything at all.
On a side note you might want to look into how to properly call procedures and how to add parameters in a way that isn't vulnerable to SQL injection.

You have to connect to the database in order to execute sql statements:
string employer = Session["Employer"].ToString();
// assume connectionString is a valid connection string
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
SqlCommand command = connection.CreateCommand();
command.CommandText = "updatework";
command.CommandType = CommandType.StoredProcedure;
command.Parameters.AddWithValue("#EmployerName", employer);
command.ExecuteNonQuery();
}

Related

Stored Procedure not working from ASP.NET

I have the following stored procedure:
alter proc SPCP_ProgramUpdate
#ID int,
#UserID int,
#Name nvarchar(150),
#University int,
#Level tinyint,
#isActive bit
as
update tblUniversityProgram set University_Fkey = #University, Level_Fkey = #Level, Program_Name = #Name, EditDate = GETDATE(), EditUser = #UserID, isActive = #isActive
where tblUniversityProgram.ID = #ID
When I run the stored procedure from SSMS, it works as intended.
However, when I run that stored procedure from ASP.NET using this code:
Dim varDbconn As New SqlConnection
Dim varDbcomm As SqlCommand
Dim varDbRead As SqlDataReader
varDbconn.ConnectionString = ConfigurationManager.ConnectionStrings("CPDB_ConnectionString").ToString
varDbconn.Open()
If Request.QueryString("program") <> "" Then
varDbcomm = New SqlCommand("SPCP_ProgramUpdate", varDbconn)
varDbcomm.CommandType = CommandType.StoredProcedure
varDbcomm.Parameters.AddWithValue("#ID", Request.QueryString("program")).DbType = DbType.Int32
varDbcomm.Parameters.AddWithValue("#UserID", Session("UserID")).DbType = DbType.Int32
varDbcomm.Parameters.AddWithValue("#University", Session("DecryptID")).DbType = DbType.Int32
varDbcomm.Parameters.AddWithValue("#Level", ddlLevel.SelectedValue).DbType = DbType.Byte
varDbcomm.Parameters.AddWithValue("#isActive", chkisActive.Checked).DbType = DbType.Boolean
varDbcomm.Parameters.AddWithValue("#Name", txttitle.Text).DbType = DbType.String
varDbcomm.ExecuteNonQuery()
varDbcomm.Dispose()
Else
....
End IF
varDbconn.Close()
nothing happens.
Any ideas?
The most likely answer to your question is that the value you are getting out of the querystring for program is not the Id in your database that you expect.
At the minute, your code is reading in input values and passing them to a stored procedure without any validation of your expected values - missing session for example could cause you all sorts of unexpected issues.
Debug your code and see exactly what parameters you are passing to your DB. Check your connection string to see that you are hitting the database where you have amended your stored procedure.
What you have should work. I would use parmaters.Add in place of addwith, but that should not really matter.
Try adding this code right after you are done setting up the parmaters:
Debug.Print("SQL = " & varDbcomm.CommandText)
For Each p As SqlParameter In varDbcomm.Parameters
Debug.Print(p.ParameterName & "->" & p.Value)
Next
That way in the debug window (or immediate depending on VS settings), you see a list of param values, and the parameter names. I suspect one of the session() values is messed up here.

Unable to update database with the Window Form Application

I am trying to update my database with the window form I have created, however an error occurred when I execute the code:
An unhandled exception of type 'System.InvalidOperationException'
occurred in System.Data.dll" at comm.ExecuteNonQuery();
Here is the code that I used to connect to my database. Was the code I used to update the database wrong?
string conn=ConfigurationManager.ConnectionStrings["MyConnection"].ConnectionString;
SqlConnection connection = new SqlConnection(conn);
SqlCommand comm = new SqlCommand("UPDATE ExerciseInstruction SET Accumulated_Daily_Sets_Completed = '0' WHERE ExerciseInstructionsID ='" + exerciseInstructionID +"'", connection);
comm.ExecuteNonQuery();
Here is the complete error message :
ExecuteNonQuery requires an open and available Connection. The
connection's current state is closed.
The error message explain all. The command cannot be executed if the code doesn't know how to reach the database. Just a call to connection.Open should fix the problem, however I think you need to use a proper way to execute the query.
This is called Parameterized query. In this way you don't concatenate strings together to form you query text but use parameters to pass values to the database engine and a special formatted string containing the parameters placeholders.
There are two main advantages to do so. It is not possible to target your code with Sql Injection hacks and you don't have to handle quoting around your strings (an infinite source of bugs)
string conn=ConfigurationManager.ConnectionStrings["MyConnection"].ConnectionString;
string cmdText = #"UPDATE ExerciseInstruction
SET Accumulated_Daily_Sets_Completed = 0
WHERE ExerciseInstructionsID =#exid";
using(SqlConnection connection = new SqlConnection(conn))
using(SqlCommand comm = new SqlCommand(cmdText, connection))
{
connection.Open(); // Need this before executing the query
comm.Parameters.Add("#exid", SqlDbType.Int).Value = exerciseInstructionID;
comm.ExecuteNonQuery();
}

prevent the sql injection in ASP .NET

I'm a new in the world of coding,
I built a large web site with several textboxes, so now i figure out that I've been using a dangerous method of inserting data in the SQL server by some thing like this:
execSQL("insert into Dossier(ID_Dossier,Nom_Giac) values(" & id_dossier.text & "," Nom_gaic.text & "')")
Public Function execSQL(ByVal req As String, Optional ByVal type As String = "r")
cmd = New SqlCommand
cmd.CommandText = req
cmd.Connection = con
openCon()
If type = "r" Then
Return cmd.ExecuteReader(CommandBehavior.CloseConnection)
Else
Return cmd.ExecuteNonQuery
End If
closeCon()
End Function
I just want to know if there is any quick way to solve this problem in my entire web site.
I applaud the fact that you want to remove any possibilities of SQL injection from your site.
That said, there's no quick, magical "find-and-replace-my-vulnerable-code" function; you need to go into your system and update any calls like that with parameterized queries.
Parameterized queries are required to prevent SQL injection. Here's an example, taken from this question: How do I create a parameterized SQL query? Why Should I?
Public Function GetBarFooByBaz(ByVal Baz As String) As String
Dim sql As String = "SELECT foo FROM bar WHERE baz= #Baz"
Using cn As New SqlConnection("Your connection string here"), _
cmd As New SqlCommand(sql, cn)
cmd.Parameters.Add("#Baz", SqlDbTypes.VarChar, 50).Value = Baz
Return cmd.ExecuteScalar().ToString()
End Using
End Function
Using LINQ to SQL can help prevent SQL Injection attacks by parameterizing for you:
LINQ to SQL passes all data to the database via SQL parameters. So, although the SQL query is composed dynamically, the values are substitued server side through parameters safeguarding against the most common cause of SQL injection attacks.
Read more about it here.

ODP.NET VB.Net calling a stored procedure and returning a refCursor

This problem has driven me mad for over a day now. I can create a connection to the database, I can execute sql and return results from that but I can't seem to call a stored Procedure. Here is the code
Dim myCMD As New OracleCommand
Dim TheDataReader as New OracleDataReader
myConnection1.Open()
myCMD.Connection = myConnection1
myCMD.CommandType = CommandType.StoredProcedure
myCMD.CommandText = "WS_DATA_LAYER.select_user_groups"
myCMD.Parameters.Add(New OracleParameter("id_user", OracleDbType.VarChar2)).Value = "TXA"
myCMD.Parameters.Add(New OracleParameter("ws_rs", OracleDbType.RefCursor)).Direction = ParameterDirection.Output
' Tried every single execute function here and none have worked
' Either error is thrown or empty refcursor
myCMD.ExecuteScalar()
TheDataReader = myCMD.Parameters(1).Value().GetDataReader()
The Problem lies in ExecuteScalar at the moment. It's throwing an exception called "Input string was not in a correct format". I've tried passing the string with Oracle single quotes and get the same thing. If I use
TheDataReader = myCMD.ExecuteQuery()
it works ok but no results are returned. I've verified that the procedure returns results for the user I'm logged in as. When the query was executing I could see a refcursor in there but it was empty. I must be going mad.
Any help is appreciated
Anyone else that may have this problem, I was passing the OracleDBType.Varchar2 as a parameter to the above VB method. But I had it declared as an integer, it needs to be explicitly passed as an OracleDBType

SQL Cache Dependency not working with Stored Procedure

I can't get SqlCacheDependency to work with a simple stored proc (SQL Server 2008):
create proc dbo.spGetPeteTest
as
set ANSI_NULLS ON
set ANSI_PADDING ON
set ANSI_WARNINGS ON
set CONCAT_NULL_YIELDS_NULL ON
set QUOTED_IDENTIFIER ON
set NUMERIC_ROUNDABORT OFF
set ARITHABORT ON
select Id, Artist, Album
from dbo.PeteTest
And here's my ASP.NET code (3.5 framework):
-- global.asax
protected void Application_Start(object sender, EventArgs e)
{
string connectionString = System.Configuration.ConfigurationManager.ConnectionStrings["MyConn"].ConnectionString;
System.Data.SqlClient.SqlDependency.Start(connectionString);
}
-- Code-Behind
private DataTable GetAlbums()
{
string connectionString =
System.Configuration.ConfigurationManager.ConnectionStrings["UnigoConnection"].ConnectionString;
DataTable dtAlbums = new DataTable();
using (SqlConnection connection =
new SqlConnection(connectionString))
{
// Works using select statement, but NOT SP with same text
//SqlCommand command = new SqlCommand(
// "select Id, Artist, Album from dbo.PeteTest", connection);
SqlCommand command = new SqlCommand();
command.Connection = connection;
command.CommandType = CommandType.StoredProcedure;
command.CommandText = "dbo.spGetPeteTest";
System.Web.Caching.SqlCacheDependency new_dependency =
new System.Web.Caching.SqlCacheDependency(command);
SqlDataAdapter DA1 = new SqlDataAdapter();
DA1.SelectCommand = command;
DataSet DS1 = new DataSet();
DA1.Fill(DS1);
dtAlbums = DS1.Tables[0];
Cache.Insert("Albums", dtAlbums, new_dependency);
}
return dtAlbums;
}
Anyone have any luck with getting this to work with SPs?
Thanks!
i figured this out, need to set query options BEFORE creating the SP. got it working when i created the SP as follows:
USE [MyDatabase]
GO
set ANSI_NULLS ON
set ANSI_PADDING ON
set ANSI_WARNINGS ON
set CONCAT_NULL_YIELDS_NULL ON
set QUOTED_IDENTIFIER ON
set NUMERIC_ROUNDABORT OFF
set ARITHABORT ON
go
create proc [dbo].[spGetPeteTest]
as
select Id, Artist, Album
from dbo.PeteTest
GO
You are not returning data from the cache every time. It should be like this:
if (Cache["Albums"]!=null)
{
return (DataTable) Cache["Albums"];
}
else
{
// you need to write coding from database.
}
Another cause can be this in a SQL statement:
AND dbo.[PublishDate] <= GetDate()
The SQLCacheDependency will behave as if the underlying data has changed even if it hasn't, since GetDate() is dynamic (equally if you were to pass DateTime.Now via a #parameter).
This was not obvious to me after re-writing my proc following all the good suggestions above, also not forgetting also to remove "SET NOCOUNT ON" from the proc. SQLCacheDependency expires the cache if the data changes OR the query parameters values change, which makes sense I suppose.
For me using something like this in the stored proc didn't work.
select id, name from dbo.tblTable;
I had to explicitly put in the references like this.
select dbo.tblTable.id, dbo.tblTable.name from dbo.tblTable;
SQL caching won't work if you use select *, also you need to make sure you put dbo (or relevant schema) in front of your table name.
You can also check SQL profiler to verify if your sql is run hope will help you etc....
Note that you cannot use
with (NOLOCK)
in the stored procedure or the the dependency will remain constantly invalid.
This does not appear to be mentioned in the documentation as far as I can tell
I realise that the original poster did not do this but anyone coming here that has the problem stated in the title may have done this so I thought it was worth mentioning.

Resources