SqlDataAdapter.Fill running SQL command twice - asp.net

I'm trying to insert a new row in my SQL database from ASP.NET but it's inserting the row twice instead of once.
I haven't been able to find which line of the code below is causing this.
Here's my code:
public static void Register(User user)
{
string query = "insert into TblTutors (username,email,pass,sub,category,city,fullname,img,bio,tutor,way)
values (#username,#email,#pass,#mat,#cat,#country,#fullname,Cast(#img As nvarchar(MAX)),#bio,#tutor,#way )";
using (SqlCommand cmd = new SqlCommand(query, con))
{
cmd.Parameters.AddWithValue("#username", user.username);
cmd.Parameters.AddWithValue("#email", user.email);
cmd.Parameters.AddWithValue("#tutor", user.tutor);
cmd.Parameters.AddWithValue("#way", user.way);
cmd.Parameters.AddWithValue("#mat", user.mat);
cmd.Parameters.AddWithValue("#cat", user.cat);
cmd.Parameters.AddWithValue("#country", user.country);
cmd.Parameters.AddWithValue("#pass", "halima");
cmd.Parameters.AddWithValue("#fullname", user.fullname);
cmd.Parameters.AddWithValue("#img", user.img);
cmd.Parameters.AddWithValue("#bio", user.bio);
con.Open();
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
sda.Fill(dt);
int i = cmd.ExecuteNonQuery();
con.Close();
}
}

DataAdapter.Fill is used to populate a DataSet with the results of the SelectCommand of the DataAdapter.
Since you're not looking to do any SELECT queries, remove the code regarding filling the DataTable as while it won't return any data, it will execute your INSERT, UPDATE and DELETE SQL commands inside cmd passed to new SqlDataAdapter(cmd);.
You're essentially writing data twice, once when you fill dt & again when you execute the query:
sda.Fill(dt);
...
int i = cmd.ExecuteNonQuery();
This should work as expected, removing the need for a DataSet as well.
public static void Register(User user)
{
string query = "insert into TblTutors (username,email,pass,sub,category,city,fullname,img,bio,tutor,way)
values (#username,#email,#pass,#mat,#cat,#country,#fullname,Cast(#img As nvarchar(MAX)),#bio,#tutor,#way )";
using (SqlCommand cmd = new SqlCommand(query, con))
{
cmd.Parameters.AddWithValue("#username", user.username);
cmd.Parameters.AddWithValue("#email", user.email);
cmd.Parameters.AddWithValue("#tutor", user.tutor);
cmd.Parameters.AddWithValue("#way", user.way);
cmd.Parameters.AddWithValue("#mat", user.mat);
cmd.Parameters.AddWithValue("#cat", user.cat);
cmd.Parameters.AddWithValue("#country", user.country);
cmd.Parameters.AddWithValue("#pass", "halima");
cmd.Parameters.AddWithValue("#fullname", user.fullname);
cmd.Parameters.AddWithValue("#img", user.img);
cmd.Parameters.AddWithValue("#bio", user.bio);
con.Open();
int i = cmd.ExecuteNonQuery();
con.Close();
}
}

Related

How do I insert grid view value into SQL Server database in ASP.NET?

I am creating a time in time out program in which when you click at a row in grid view it gets the data of the employee's last name, first name and middle name, then when I click the button, that data will be inserted to an inner joined table which is the time in time out table where the employee is set as Lname + Fname + Mname AS Employee_name
Here is my code - I need help with inserting the grid view data
SqlConnection con = new
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["connect"].ConnectionString);
string command = "INSERT INTO DTR(EmpRegID, CheckIn) VALUES (#EmpRegID, #CheckIn)";
SqlCommand cmd = new SqlCommand(command, con);
cmd.Parameters.AddWithValue("#CheckIn", DateTime.Now.ToString());
try
{
con.Open();
cmd.ExecuteNonQuery();
GridView2.DataBind();
}
finally
{
con.Close();
}
finally i have done it thank you guys for your answers so here is the code
string test1 = test.SelectedRow.Cells[1].Text;
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["connect"].ConnectionString);
string command = "INSERT INTO DTR(RegEmpID, CheckIn) VALUES (#RegEmpID, #CheckIn)";
SqlCommand cmd = new SqlCommand(command, con);
cmd.Parameters.AddWithValue("#RegEmpID", test1);
cmd.Parameters.AddWithValue("#CheckIn", DateTime.Now.ToString());
try
{
con.Open();
cmd.ExecuteNonQuery();
GridView2.DataBind();
}
finally
{
con.Close();
}

The variable name #IdLiquidacion has already been declared. Variable names must be unique within a query batch or stored procedure.'

I have the following problem when inserting the info in the databases
public void Insertar()
{
SqlConnection con = new SqlConnection();
con.ConnectionString = "Data Source=BD-DLLO-SP2016;Initial Catalog=GobernacionCesar;Integrated Security=True";
con.Open();
string query = "INSERT INTO Liquidacion (IdLiquidacion, IdPeriodo, FechaGeneracion, Usuario) VALUES(#IdLiquidacion, #IdPeriodo, #FechaGeneracion, #Usuario)";
SqlCommand com1 = new SqlCommand(query, con);
foreach (GridViewRow gridRow in GridView4.Rows)
{
Iniciar();
com1.Parameters.AddWithValue("#IdLiquidacion", A);
com1.Parameters.AddWithValue("#IdPeriodo", cell);
com1.Parameters.AddWithValue("#FechaGeneracion", DateTime.Now.ToString());
com1.Parameters.AddWithValue("#Usuario", gridRow.Cells[0].Text);
com1.ExecuteNonQuery();
}
con.Close();
return;
}
Move the command
SqlCommand com1 = new SqlCommand(query, con);
to the beginning of the loop:
foreach (GridViewRow gridRow in GridView4.Rows)
{
SqlCommand com1 = new SqlCommand(query, con);
....
}
You should
define the parameters outside of the loop
only set the values for the parameters inside the loop
Like this:
SqlCommand com1 = new SqlCommand(query, con);
// define parameters - you need to adapt the datatypes - I was only guessing
com1.Parameters.Add("#IdLiquidacion", SqlDbType.Int);
com1.Parameters.Add("#IdPeriodo", SqlDbType.VarChar, 50);
com1.Parameters.Add("#FechaGeneracion", SqlDbType.DateTime);
com1.Parameters.Add("#Usuario", SqlDbType.VarChar, 100);
foreach (GridViewRow gridRow in GridView4.Rows)
{
Iniciar();
// inside the loop, only SET the values
com1.Parameters["#IdLiquidacion"].Value = A;
com1.Parameters["#IdPeriodo"].Value = cell;
com1.Parameters["#FechaGeneracion"].Value = DateTime.Now;
com1.Parameters["#Usuario"].Value = gridRow.Cells[0].Text;
com1.ExecuteNonQuery();
}
You're adding the parameters in the loop. If you clear them before adding, this should work.

why does SELECT SCOPE_IDENTITY() returning null?

I am trying to get ID generated by last Insert function. I understand very little about Scope and Session. But by reading blogs and other sources, I understood that, I should use Scope_Identity() function. But I am getting null value. Here is my code :
public int InsertUser(string username, string gender, string agegroup, string email, int partnerID, string userType)
{
try
{
string query = "Insert into tblUser (username,gender,agegroup,email,partnerid,usertype) values (#username,#gender,#age,#email,#partnerid,#usertype)";
SqlCommand cmd = new SqlCommand(query, _dbConnection.getCon());
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("#username", username);
cmd.Parameters.AddWithValue("#gender", gender);
cmd.Parameters.AddWithValue("#age", agegroup);
cmd.Parameters.AddWithValue("#email", email);
cmd.Parameters.AddWithValue("#partnerid", partnerID);
cmd.Parameters.AddWithValue("#usertype", userType);
if (cmd.ExecuteNonQuery() > 0)
{
query = "select scope_identity() as id";
cmd = new SqlCommand(query, _dbConnection.getCon());
SqlDataAdapter adp = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
adp.Fill(dt);// dt is showing no value in it
return 1;// This should return ID
}
else {
return -1;
}
}
catch (Exception e) {
throw e;
}
}
How can I achieve this?
Try appending SELECT scope_identity() to your first query and then capture the identity using var identity = cmd.ExecuteScalar() instead of running cmd.ExecuteNonQuery().

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

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

Resources