Table expects a parameter which already exists - asp.net

ALTER PROCEDURE tableuser
-- Add the parameters for the stored procedure here
#userName varchar(50)
AS
IF EXISTS(SELECT 'True' FROM tbl_user WHERE userName = #userName)
BEGIN
--This means it exists, return it to ASP and tell us
SELECT 'This record already exists!'
END
ELSE
BEGIN
--This means the record isn't in there already, let's go ahead and add it
SELECT 'Record Added'
INSERT into tbl_user(userName) VALUES(#username)
END
This is my code in sql server management studio and below is the C# code:
protected void Button1_Click(object sender, EventArgs e)
{
SqlCommand cmd = new SqlCommand("tableuser", conn);
conn.Open();
SqlParameter param = new SqlParameter();
cmd.Parameters.AddWithValue("#userName", uname.Text);
param.Value = uname.Text;
cmd.Parameters.Add(param);
SqlDataReader reader = cmd.ExecuteReader();
if (reader.HasRows)
{
Response.Write("Username exists");
}
else
{
cmd.Parameters.AddWithValue("#userName", uname.Text);
cmd.CommandType = System.Data.CommandType.StoredProcedure;
conn.Open();
cmd.ExecuteNonQuery();
Response.Write("Successfully saved...!!!");
conn.Close();
}
}
}
The error comes is: Procedure or function 'tableuser' expects parameter '#userName', which was not supplied.

This should work:
conn.Open();
var cmd = new SqlCommand("tableuser", conn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#userName", uname.Text);
var rdr = cmd.ExecuteReader();
rdr.Read();
Response.Write(rdr.GetString(0));
conn.Close();

Related

I try to update name record but I can't

protected void submit_Click(object sender, EventArgs e)
{
Label2.Text = Session["id"].ToString();
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnString"].ConnectionString);
SqlCommand cmd = con.CreateCommand();
con.Open();
string UpdateQuery = "Update register set name='" + name.Text + "'where email='" + Session["id"] + "'";
SqlCommand cmd3 = new SqlCommand(UpdateQuery, con);
cmd3.CommandType = CommandType.Text;
con.Close();
}
}
I want to update name record using session for user profile in asp.net.
Try like this:
using (SqlConnection conn =
new SqlConnection(ConfigurationManager.ConnectionStrings["ConnString"].ToString()))
{
string strSQL = "UPDATE register set [name] = #name " +
"WHERE email = #email";
using (SqlCommand cmd = new SqlCommand(strSQL, conn))
{
cmd.Parameters.Add("#name", SqlDbType.NVarChar).Value = name.Text;
cmd.Parameters.Add("#email", SqlDbType.NVarChar).Value = Session["id"].ToString();
conn.Open();
cmd.ExecuteNonQuery();
}
}
The above will dispose/close the connection for you. And this will even close the connection if you have some error in the code.
The above also removes the messy "'" and concatenation in your code (easy to read, and maintain). And by using parameter's the code is also safe from injection.
hence:

how to store primary key in session with stored procedure

I have login page for which I have used stored procedure. I am using session to store id of user which is primary key. When I enter wrong username and password it should redirect to some other page but it is giving me exception as "Object reference not set to an instance of an object." My code for login.aspx.cs is:
SqlCommand cmd1 = new SqlCommand("select artistId from artist where Username=#username and Artistpass=#password",con);
cmd1.Parameters.AddWithValue("#username", txtusr.Text);
cmd1.Parameters.AddWithValue("#password", txtpass.Text);
con.Close();
Session["username"] = txtusr.Text;
SqlParameter param = new SqlParameter("#username", txtusr.Text.Trim());
SqlParameter param1 = new SqlParameter("#password", txtpass.Text.Trim());
SqlCommand cmd = new SqlCommand("login", con);
cmd.Parameters.Add(param);
cmd.Parameters.Add(param1);
cmd.CommandType = CommandType.StoredProcedure;
con.Open();
SqlDataReader dr = cmd.ExecuteReader();
if (dr.Read())
{
Response.Redirect("afterlogin.aspx");
}
else
{
MessageBox.Show("Login Unsuccessful");
}
con.Close();
if (con.State != ConnectionState.Open)
{
con.Open();
}
int id = (int)cmd1.ExecuteScalar();
Session["ID"] = id;
con.Close();
plz help.
ExecuteScalar returns null if your where statement doesn't find a match for your user and password
So you cannot cast a null return value to an integer
object id = cmd1.ExecuteScalar();
Session["ID"] = id;
con.Close();
this, of course, means that you need to check the Session["ID"] variable in the redirected page to see it it is null

asp.net login web page using sql server

i am stuck in my login page..my button click event is as follows:
protected void Button1_Click(object sender, EventArgs e)
{
string cs = "Data Source=ims-aab46237892;Initial Catalog=Inventory;Integrated Security=True";
string SelectString = "SELECT COUNT(*) FROM user WHERE username = #Username AND password = #Password";
SqlConnection con = new SqlConnection(cs);
SqlCommand cmd = new SqlCommand(SelectString,con);
cmd.Connection = con;
cmd.CommandType = CommandType.Text;
cmd.CommandText = SelectString;
SqlParameter username = new SqlParameter("#Username",SqlDbType.VarChar,50);
username.Value = TextName.Text.Trim().ToString();
cmd.Parameters.Add(username);
SqlParameter password = new SqlParameter("#Password", SqlDbType.VarChar, 50);
password.Value = TextPass.Text.Trim().ToString();
cmd.Parameters.Add(password);
con.Open();
if(cmd.ExecuteScalar() != null)
Response.Redirect("Home.aspx");
else
Response.Redirect("wrongpasspage.aspx");
con.Close();
}
and my data table has the required username and password fields.. error i am getting is incorrect syntax near keyword user... plz help
user is a reserved keyword in SQL server. Try [user] or rename your table to Users.
use [user] instead of user in SelectString statement.

sql stored procedure in asp.net not running

A little background on what I'm doing.
I have a button that has a click call which takes me to this code.
static public DataSet shareFiles(TransitoryRegObj argTransRegObj)
{
string sqlString = "do_share_files"; // it's a stored procedure
SqlConnection cnn = new SqlConnection(masterConn);
SqlCommand comm = new SqlCommand(sqlString, cnn);
DataSet ds = new DataSet();
try
{
cnn.Open();
SqlCommand Comm = new SqlCommand(sqlString, cnn);
Comm.CommandType = CommandType.StoredProcedure;
comm.Dispose();
cnn.Close();
return ds;
}
catch (Exception ex)
{
// log here should anything go wrong with anything
// lblmessage.Text = "Error: " + ex.Message;
if (comm != null)
comm.Dispose();
if (cnn != null)
cnn.Close();
DataTable dt = new DataTable("ExceptionTable");
dt.Columns.Add("ExceptionMessage");
dt.Rows.Add(ex.Message);
ds = new DataSet();
ds.Tables.Add(dt);
return ds;
}
}
The code runs fine however nothing is written to database. here is do_share_files stored procedure.
ALTER PROCEDURE [dbo].[do_share_files]
--#device_id bigint, #user_id bigint, #file_name varchar(50),#full_up_path varchar(50), #upLength varchar(30)
--,#mime_type varchar(20), #filedate varchar(30)
AS
BEGIN
insert into [user_files] (device_id, user_id, original_name, original_path, up_path, content_type, up_dt)
values (17, 30, 'test.pg', 'test.pg', 'test.pg','test.pg', '2012-11-15 03:58:06.043')
END
I have static values for now since i'm just trying to get it to run to stored procedure.
I'm new to asp.net and don't know what i'm doing wrong. Any help would be appreciated.
Thanks!
You could start with this:
static public DataSet shareFiles(TransitoryRegObj argTransRegObj)
{
string sqlString = "do_share_files"; // it's a stored procedure
DataSet ds = new DataSet();
try
{
using (var cnn = new SqlConnection(masterConn))
{
SqlCommand comm = new SqlCommand(sqlString, cnn);
comm.CommandType = CommandType.StoredProcedure;
cnn.Open();
comm.ExecuteNonQuery ();
To summarize:
Comm and comm are different commands;
To run the proc, you need to call ExecuteNonQuery or other Execute method.
Your code has few mistakes
1. I cant understand why you are using this line twice
SqlCommand comm = new SqlCommand(sqlString, cnn);
2. You didnot execute the procedure which is the main problem
static public DataSet shareFiles(TransitoryRegObj argTransRegObj)
{
try
{
string sqlString = "do_share_files"; // it's a stored procedure
SqlConnection cnn = new SqlConnection(masterConn);
SqlCommand comm = new SqlCommand(sqlString, cnn);
DataSet ds = new DataSet();
cnn.Open();
Comm.CommandType = CommandType.StoredProcedure;
comm.ExecuteNonQuery();
comm.Dispose();
cnn.Close();
return ds;
}
catch (Exception ex)
{
//something here
}
}

sql data reader class

I did sql command with SqlDataReader but I had this error
System.IndexOutOfRangeException: UserName
Page Load event:
protected void Page_Load(object sender, EventArgs e)
{
using (SqlConnection con = Connection.GetConnection())
{
SqlCommand Com = new SqlCommand("Total", con);
Com.CommandType = CommandType.StoredProcedure;
SqlDataReader Dr = Com.ExecuteReader();
if (Dr.Read())
{
string Result= Dr["UserName"].ToString();
Lbltotal.Text = Result;
}
}
}
Stored Procedure:
Alter proc Total
as
begin
select Count (UserName) from Registration
end
Change your storder procedure to:
Alter proc Total
as
begin
select Count (UserName) as UserName from Registration
end
You're not returning any column called UserName - you're just returning a count which has no explicit column name.
If you have something like this - just a single value - you could also use the ExecuteScalar method which will return exactly one value:
using(SqlCommand Com = new SqlCommand("Total", con))
{
Com.CommandType = CommandType.StoredProcedure;
int count = (int)Com.ExecuteScalar();
}
If you insist on using the SqlDataReader, you just need to use a positional parameter:
using(SqlCommand Com = new SqlCommand("Total", con))
{
Com.CommandType = CommandType.StoredProcedure;
using(SqlDataReader Dr = Com.ExecuteReader())
{
if (Dr.Read())
{
string Result= Dr[0].ToString(); // take value no. 0 - the first one
Lbltotal.Text = Result;
}
}
}

Resources