sql stored procedure in asp.net not running - asp.net

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
}
}

Related

Detailsview in ASP.NET

I am trying to hit sql server with objectdatasource and return a datatable to fill my details view control. the selected ID value is returned by a gridview control. It seems like the datatable is not filled by adapter, and i couldn't figure out why. The ID in sql is set as a primary key (Int, 4, not null). The debugger says the Detail datatable is null. Any help is much appreciated.
public DataTable GetDetail(string ID)
{
if (ID == "")
{
return null;
}
else
{
DataTable Detail = null;
using (SqlConnection conn = new SqlConnection(connection))
{
string comm = #"select * from dbo.Products where ID = #ID";
conn.Open();
SqlDataAdapter adapter=null;
using (SqlCommand cmd = new SqlCommand(comm, conn))
{
cmd.Parameters.Add("ID", System.Data.SqlDbType.Int, 4).Value = Convert.ToInt32(ID);
adapter = new SqlDataAdapter(cmd);
adapter.Fill(Detail);
return Detail;
}
}
}
I think you missed the commandType
cmd.CommandType = CommandType.Text;
Try this
DataSet ds = new DataSet();
using (SqlConnection con = new SqlConnection(connection))
{
string myquery="select * from dbo.Products where ID = #ID";
SqlCommand cmd = new SqlCommand(myquery, con);
SqlDataAdapter dap = new SqlDataAdapter();
dap.SelectCommand = cmd;
cmd.Parameters.Add("#ID", SqlDbType.NVarChar, 15).Value = ID;
dap.Fill(ds);
return ds.Tables[0];
}
Thanks for ALL.
The problem is I didnt initialize my datatable to a new instance.
DataTable Detail = null; ===> DataTable Detail = new Datatable();
and also the convert should be done in sql not in codes.
cmd.Parameters.Add("ID", System.Data.SqlDbType.Int, 4).Value = ID;
string comm = #"select * from dbo.Products where ID = convert(int,#ID)";

i want to use data reader & update statement at same time

here is code
String[] month=new String[12]{"January","February","March","April","May","June","July","August","September","Octomber","November","December"};
int day = DateTime.Now.Day;
int mon= DateTime.Now.Month;
mon = mon - 1; //because month array is with 0
Label1.Text = day.ToString();
if (day==21)
{
int j = 1;
SqlCommand cmd1 = new SqlCommand();
cmd1.Connection = MyConn;
cmd1.CommandText = "SELECT No_of_times,Dustbin_no from mounthly_data";
SqlDataReader MyReader = cmd1.ExecuteReader();
while (MyReader.Read())
{
String a = MyReader["No_of_times"].ToString();
String b = MyReader["Dustbin_no"].ToString();
SqlCommand cmd = new SqlCommand();
cmd.Connection = MyConn;
cmd.CommandText = "update Yearly_data set [" + month[mon] + "]='"+a+"' where Dustbin_no='"+b+"'"; //just see ["+month[mon+"] it's imp
i = cmd.ExecuteNonQuery();
}
MyReader.Close();
}
i got error as
There is already an open DataReader associated with this Command which must be closed first.
I think you should give us the rest of the code above this code block because I'm not sure how a ExecuteNonQuery is using up a datareader. But from what I can gather, what you probably want is to open two separate connections. Only one datareader can be open per connection at a time. Either you use two separate connections or you could maybe use a datatable/dataset for the result of both your queries.
EDIT: From the rest of your code, yes, using two connections would be the simplest answer. When a reader is open, the connection associated with it is dedicated to the command that is used, thus no other command can use that connection.
I would recommend using a DataTable as this OLEDB example shows:
public static void TrySomethingLikeThis()
{
try
{
using (OleDbConnection con = new OleDbConnection())
{
con.ConnectionString = Users.GetConnectionString();
con.Open();
OleDbCommand cmd = new OleDbCommand();
cmd.Connection = con;
cmd.CommandType = CommandType.Text;
cmd.CommandText = "SELECT * FROM Customers";
OleDbDataAdapter da = new OleDbDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
foreach (DataRow row in dt.AsEnumerable())
{
cmd.CommandText = "UPDATE Customers SET CustomerName='Ronnie' WHERE ID = 4";
cmd.ExecuteNonQuery();
}
}
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}

how to write select parameterized query in asp.net

Below code is written to call parameterized select query in asp.net
public bool checkConflictTime()
{
bool TimeExists = false;
DataSet ds = new DataSet();
SqlConnection sqlconn = new SqlConnection();
sqlconn.ConnectionString = ConfigurationManager.ConnectionStrings["TestConn"].ConnectionString;
string sql = #"SELECT * FROM Images WHERE starttime= #starttime AND endtime = #endtime";
SqlCommand sqlcommand = new SqlCommand(sql,sqlconn);
//sqlcommand.Connection = sqlconn;
//string sql = "CheckConflictTimings";
sqlcommand.CommandType = CommandType.Text;
sqlcommand.CommandText = sql;
sqlcommand.Parameters.Add(new SqlParameter("#starttime", ddlStartTime.SelectedItem.Text));
sqlcommand.Parameters.Add(new SqlParameter("#endtime", ddlEndTime.SelectedItem.Text));
SqlDataAdapter da = new SqlDataAdapter(sql, sqlconn);
try
{
da.Fill(ds);
if (ds.Tables[0].Rows.Count > 0)
{
TimeExists = true;
}
}
catch (Exception ex)
{
}
finally
{
sqlconn.Close();
sqlconn.Dispose();
}
return TimeExists;
}
Is there something wrong? it threw error of :Must declare the scalar variable "#starttime"
when filling data adapter.
Try
SqlDataAdapter da = new SqlDataAdapter(sqlcommand);
Try
sqlcommand.Parameters.Add(new SqlParameter("starttime", ddlStartTime.SelectedItem.Text));
I don't think you need the # prefix when adding the parameter.
I think you're not passing your command as a SelectCommand to the adapter.
da.SelectCommand = sqlcommand;
Try
sqlcommand.Parameters.AddWithValue("#starttime",ddlStartTime.SelectedItem.Text);
instead of
sqlcommand.Parameters.Add(new SqlParameter("#starttime", ddlStartTime.SelectedItem.Text));

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;
}
}
}

how to from select parameterized query in asp.net

I want to write parametrized query for select statement. but it gives exception that "Must declare the variable '#'." how to declare this variable .
My code is given below:
SqlConnection con = null;
SqlCommand cmd = null;
try
{
//int #[MONTH_FOR], #[YEAR_FOR];
con = new SqlConnection("Data Source=192.168.10.3;Initial Catalog=GPSTrainees;user id=gp;password=gp");
con.Open();
string select = #"SELECT [COMPONENT_NAME] ,[COMPONENT_AMOUNT]
FROM [GoalPlanForTrainees].[gp].[TEAM_FUNDS_DETAILS]
WHERE [MONTH_FOR] = #[MONTH_FOR] AND [YEAR_FOR] = #[YEAR_FOR]";
cmd = new SqlCommand(select, con);
cmd.Parameters.Add(new SqlParameter("#[MONTH_FOR]", Convert.ToInt32( TextBox1.Text.Trim())));
cmd.Parameters.Add(new SqlParameter("#[YEAR_FOR]",Convert.ToInt32(TextBox2.Text.Trim())));
DataSet ds = new DataSet();
SqlDataAdapter adp = new SqlDataAdapter(select, con);
adp.Fill(ds);
GridView1.DataSource = ds;
GridView1.DataBind();
}
catch (Exception ex)
{
}
finally
{
if (con != null)
{
con.Close();
}
}`enter code here`
While creating the parameters, please remove the "#" in front of the Parameter name. Something like this:
cmd.Parameters.Add(new SqlParameter("[MONTH_FOR]", Convert.ToInt32(TextBox1.Text.Trim())));
Hopefully this should help.
Put the variable declaration in the sql statement. So move int #[MONTH_FOR], #[YEAR_FOR];
to
#"int #[MONTH_FOR], #[YEAR_FOR]; SELECT [COMPONENT_NAME] ,[COMPONENT_AMOUNT] FROM [GoalPlanForTrainees].[gp].[TEAM_FUNDS_DETAILS] WHERE [MONTH_FOR] = #[MONTH_FOR] AND [YEAR_FOR] = #[YEAR_FOR]";
Cheers Tigger
try this
int MONTH_FOR=#monthFor
command.Parameters.Add(MONTH_FOR, SqlDbType.int).Value = value

Resources