Why insert statement generates 2 rows? - asp.net

I dont know why, but when I do an insert statement in my project, its generate 2 indentical rows instead of makeing just one.
why is that ?
this is my code :
if (ListBox.Items.Count != 0)
{
string username = Session["Session"].ToString();
con = new SqlConnection("Data Source=MICROSOF-58B8A5\\SQL_SERVER_R2;Initial Catalog=Daniel;Integrated Security=True");
con.Open();
string knowWhichOne = "SELECT ID FROM Users WHERE Username='" + UserOrGuest.Text + "'";
SqlCommand comm = new SqlCommand(knowWhichOne, con);
int userID = (Int32)comm.ExecuteScalar();
knowWhichOne = "SELECT ClassID FROM Users WHERE Username='" + UserOrGuest.Text + "'";
comm = new SqlCommand(knowWhichOne, con);
int classID = (Int32)comm.ExecuteScalar();
knowWhichOne = "SELECT SchoolID FROM Users WHERE Username='"+UserOrGuest.Text + "'";
comm = new SqlCommand(knowWhichOne, con);
int schoolID = (Int32)comm.ExecuteScalar();
if (RadioWords.Checked == true)
{
game = 1;
}
else
{
game = 2;
}
string arr = "";
for (int i = 0; i < ListBox.Items.Count; i++)
{
arr += ListBox.Items[i] +",";
}
string sqlqueryString = "INSERT INTO HistoryOfGames (GameID, UserID, LengthOfArray, NumberOfErrors, ClassID, SchoolID,Arrayarray) VALUES (#GameID, #UserID, #LengthOfArray, #NumberOfErrors, #ClassID, #SchoolID, #Arrayarray);" + "SELECT SCOPE_IDENTITY()";
SqlCommand commandquery = new SqlCommand(sqlqueryString, con);
commandquery.Parameters.AddWithValue("GameID", game);
commandquery.Parameters.AddWithValue("UserID", userID);
commandquery.Parameters.AddWithValue("LengthOfArray", HowMany.Text);
commandquery.Parameters.AddWithValue("NumberOfErrors", 0);
commandquery.Parameters.AddWithValue("ClassID", classID);
commandquery.Parameters.AddWithValue("SchoolID", schoolID);
commandquery.Parameters.AddWithValue("Arrayarray", arr);
commandquery.ExecuteNonQuery();
int IdOfRecentHistoryGame = (int)(decimal)commandquery.ExecuteScalar();
con.Close();
Response.Redirect("NowPlay.aspx?ID="+ IdOfRecentHistoryGame);
}

You're running it twice, ExecuteNonQuery() and ExecuteScalar(). Get rid of the ExecuteNonQuery().

you do
commandquery.ExecuteNonQuery();
then right after
int IdOfRecentHistoryGame = (int)(decimal)commandquery.ExecuteScalar();
you do execute it twice
and don't forget to check for sql injection in your code...

I'd check two things:
see how many times this statement is executed (try setting a breakpoint to verify that the code is only run once)
see if there are any triggers in the database that might cause an extra record to be inserted

I had the same problem,I handled it this way.not professional but it works:
Dim x As Boolean = True
If x = True Then
here goes your code to insert to database.
End If
x = False

Related

How to store a select query result ( one result ) to a variable using executescalar() ? ( ASP.NET )

i have to store a select query result in a variable .i'm new in asp.net . i used executescalar but it doesn't work. i try many times but i failed here my last try :
using (SqlConnection sqlConnection = new SqlConnection())
{
var connetionString = ConfigurationManager.ConnectionStrings["connections"].ToString();
sqlConnection.ConnectionString = connetionString;
string sql = "Select sum((prime_comptant+10)*0.12) from mvt_garantie_quittance where numero_quittance='" + numQuittance + "'";
SqlDataAdapter adapter = new SqlDataAdapter(sql, sqlConnection);
DataSet dataset = new DataSet();
adapter.Fill(dataset);
string result = dataset.Tables[0].ToString();
}
Can you fix the code to me? i have to store the result in a variable
string sql = "Select sum((prime_comptant+10)*0.12) from mvt_garantie_quittance where numero_quittance='" + numQuittance + "'";
var connetionString = ConfigurationManager.ConnectionStrings["connections"].ToString();
string result = null;
using (SqlConnection conn = new SqlConnection(connetionString))
{
SqlCommand cmd = new SqlCommand(sql, conn);
conn.Open();
result = cmd.ExecuteScalar().ToString();
}

Insert records in database in which have 3 foreign keys

I'm trying to insert a record in the table but the problem is in that table have 3 foreign keys. I'll be using dataTable for that but it gives an error 'There is no row position at 0'
                             
There is my code:
try
{
using (var sqlConnection = new Helpers.SqlConnectionHelpers())
{
var connection = sqlConnection.OpenConnection();
command = new SqlCommand("CarSold_Insert", connection);
command.CommandType = CommandType.StoredProcedure;
SqlCommand commandTwo = new SqlCommand("SELECT CarForSaleId, UserId, SalesPersonId FROM CarSold WHERE Price = '" + txtPrice.Text + "'", connection);
DataTable table = new DataTable();
DataSet dataSet = new DataSet();
table.Load(commandTwo.ExecuteReader());
var carForSaleId = table.Rows[0]["CarForSaleId"].ToString();
var userId = table.Rows[0]["UserId"].ToString();
var salesPersonId = table.Rows[0]["SalesPersonId"].ToString();
command.Parameters.AddWithValue("CarForSaleId", carForSaleId);
command.Parameters.AddWithValue("UserId", userId);
command.Parameters.AddWithValue("SalesPersonId", salesPersonId);
command.Parameters.AddWithValue("Price", txtPrice.Text);
command.Parameters.AddWithValue("DateSold", dateSold);
command.Parameters.AddWithValue("MonthlyPaymentDate", monthlyPaymentDate);
command.Parameters.AddWithValue("MonthlyPaymentAmount", txtPaymentAmount.Text);
//connection.Open();
int k = command.ExecuteNonQuery();
command.Parameters.Clear();
if (k != 0)
{
Response.Redirect("~/AdminPanel/CarSold.aspx");
}
else
{
lblAns.Text = "Record Not Inserted into the database";
lblAns.ForeColor = System.Drawing.Color.Red;
}
}
}
catch (Exception ex)
{
lblAns.Text = ex.Message;
}
Since Price column is float you need to write query with query parameter like this:
SqlCommand commandTwo = new SqlCommand("SELECT CarForSaleId, UserId, SalesPersonId FROM CarSold WHERE Price = #Price", connection);
commandTwo.Parameters.AddWithValue("#Price", txtPrice.Text);
The above mentioned command will give return you the carForSaleId, userId, salesPersonId which you will use in the insert command

error:Must declare the scalar variable "#ID" asp.net & sql server2014

asp.net & sql server 2014 : why this error appearMust declare the scalar variable"#ID" I looked on goggle and I think it has something to do with insert parameters for ID. Then again I read there could be a typo error.
As I am not going to insert ID column manually I think this is why I am having problem(s) and I don't know how to solve this problem. i cant find out what is missing or wrong could you help please
string query = "insert into LegRent(ID, Day, Date, Name, Nationality, relegon, NatID, Name2, Nationality2, relegon2, NatID2, Type, Building, Flat, UseFor, Duration, StartFrom, EndIn, RentValue, OnlyAr, YearPercent, InsuranceValue, OnlyArInsur, Addres2, Addres) values (#ID, #Day, #Date, #Name, #Nationality, #relegon, #NatID, #Name2, #Nationality2, #relegon2, #NatID2, #Type, #Building, #Flat, #UseFor, #Duration, #StartFrom, #EndIn, #RentValue, #OnlyAr, #YearPercent, #InsuranceValue, #OnlyArInsur, #Addres2, #Addres)";
try
{
string query2 = "Select ##Identity";
int ID;
string connect = "Provider=SQLOLEDB;Data Source=.;Initial Catalog=Construction;Integrated Security=SSPI;";
using (OleDbConnection conn2 = new OleDbConnection(connect))
{
using (OleDbCommand cmd = new OleDbCommand(query, conn2))
{
cmd.Parameters.AddWithValue("#ID", idtxt.Text);
cmd.Parameters.AddWithValue("#Day", daytxt.Text);
cmd.Parameters.AddWithValue("#Date", datetxt.Text);
cmd.Parameters.AddWithValue("#Name", namedd.Text);
cmd.Parameters.AddWithValue("#Nationality", ddNati.Text);
cmd.Parameters.AddWithValue("#relegon", ddRelgon.Text);
cmd.Parameters.AddWithValue("#NatID", NatIDtxt.Text);
cmd.Parameters.AddWithValue("#Name2", namedd2.Text);
cmd.Parameters.AddWithValue("#Nationality2", ddNati2.Text);
cmd.Parameters.AddWithValue("#relegon2", ddRelgon2.Text);
cmd.Parameters.AddWithValue("#NatID2", NatIDtxt2.Text);
cmd.Parameters.AddWithValue("#Type", typrdd.Text);
cmd.Parameters.AddWithValue("#Building", buileddd.Text);
cmd.Parameters.AddWithValue("#Flat", flatdd.Text);
cmd.Parameters.AddWithValue("#UseFor", usetxt.Text);
cmd.Parameters.AddWithValue("#Duration", durationtxt.Text);
cmd.Parameters.AddWithValue("#StartFrom", starttxt.Text);
cmd.Parameters.AddWithValue("#EndIn", endtxt.Text);
cmd.Parameters.AddWithValue("#RentValue", vluetxt.Text);
cmd.Parameters.AddWithValue("#OnlyAr", onlytxt.Text);
cmd.Parameters.AddWithValue("#InsuranceValue", insurtxt.Text);
cmd.Parameters.AddWithValue("#OnlyArInsur", insuronlytxt.Text);
cmd.Parameters.AddWithValue("#YearPercent", percenttxt.Text);
cmd.Parameters.AddWithValue("#Addres2", adresstxt2.Text);
cmd.Parameters.AddWithValue("#Addres", adresstxt.Text);
conn2.Open();
cmd.ExecuteNonQuery();
cmd.CommandText = query2;
ID = (int)cmd.ExecuteScalar();
lbl_msg.Text = "تـــم الحفظ";
int rentMonths = 0;
bool isInt = int.TryParse(durationtxt.Text, out rentMonths);
if (isInt)
{
for (int index = 0; index < rentMonths; index++)
{
OleDbCommand insertRentMonths = new OleDbCommand("INSERT INTO [dbo].[AccRentReceipt] ([ReceiptID] ,[ContractID] ,[Name]) VALUES (#ReceiptID ,#ContractID ,#Name)", conn2);
cmd.Parameters.AddWithValue("#ReceiptID", index + 1);
cmd.Parameters.AddWithValue("#ContractID", ID);
cmd.Parameters.AddWithValue("#Name", namedd.Text);
}
}
}
}
}
catch (Exception ex)
{
lbl_msg.Text = "خطــــأ " + ex.Message;
}

Refuses to make ExecuteNonQuery : Incorrect syntax near '('

Im trying to insert data to my database, and it gives me an error :
Incorrect syntax near '('.
This is my code :
string username = Session["Session"].ToString();
con = new SqlConnection("Data Source=MICROSOF-58B8A5\\SQL_SERVER_R2;Initial Catalog=Daniel;Integrated Security=True");
con.Open();
string knowWhichOne = "SELECT ID FROM Users WHERE Username='" + UserOrGuest.Text + "'";
SqlCommand comm = new SqlCommand(knowWhichOne, con);
int userID = (Int32)comm.ExecuteScalar();
knowWhichOne = "SELECT ClassID FROM Users WHERE Username='" + UserOrGuest.Text + "'";
comm = new SqlCommand(knowWhichOne, con);
int classID = (Int32)comm.ExecuteScalar();
knowWhichOne = "SELECT SchoolID FROM Users WHERE Username='"+UserOrGuest.Text + "'";
comm = new SqlCommand(knowWhichOne, con);
int schoolID = (Int32)comm.ExecuteScalar();
if (RadioWords.Checked == true)
{
game = 1;
}
else
{
game = 2;
}
string sqlqueryString = "INSERT INTO (GameID, UserID, LengthOfArray, NumberOfErrors, ClassID, SchoolID) VALUES (#GameID, #UserID, #LengthOfArray, #NumberOfErrors, #ClassID, #SchoolID)";
SqlCommand commandquery = new SqlCommand(sqlqueryString, con);
commandquery.Parameters.AddWithValue("GameID", game);
commandquery.Parameters.AddWithValue("UserID", userID);
commandquery.Parameters.AddWithValue("LengthOfArray", HowMany.Text);
commandquery.Parameters.AddWithValue("NumberOfErrors", 0);
commandquery.Parameters.AddWithValue("ClassID", classID);
commandquery.Parameters.AddWithValue("SchoolID", schoolID);
commandquery.ExecuteNonQuery();
con.Close();
I run it in debug mode, and its accepting everything until the "ExecuteNonQuery();" line.
anybody has a clue what I did wrong?
Thanks!
you did this:
INSERT INTO (GameID....
but should do this:
INSERT INTO tablename (GameID....
Your INSERT INTO statement is missing the name of the table into which it is supposed to insert.
The syntax of your insert into statement is incorrect as you are not specifying which table you are inserting into.
The correct syntax is
INSERT INTO table_name (column1, column2, column3,...)
VALUES (value1, value2, value3,...)
See : http://www.w3schools.com/sql/sql_insert.asp for more information

insert a database value to a string array - not working

Cheers,
Im trying to insert a database value to my string array.
for some reason, it says :
"Object reference not set to an instance of an object."
This is my code :
if (IsPostBack)
{
if (RadioWords.Checked == true)
{
con = new SqlConnection("Data Source=MICROSOF-58B8A5\\SQL_SERVER_R2;Initial Catalog=Daniel;Integrated Security=True");
con.Open();
string SqlCount = "SELECT COUNT(*) FROM WordGame";
SqlCommand command = new SqlCommand(SqlCount, con);
//Sets an array of the size of the database.
int count = (Int32)command.ExecuteScalar();
arrOfWords = new string[count];
//Initialize the words in the array.
for (int i = 0; i < arrOfWords.Length; i++)
{
int GetRandomNumber = rnd.Next(1, arrOfWords.Length);
string Sqlinsert = "SELECT Word FROM WordGame WHERE ID='"+GetRandomNumber+"'";
SqlCommand commandToRandom = new SqlCommand(Sqlinsert, con);
arrOfWords[i] = commandToRandom.ExecuteScalar().ToString();
}
}
and its refering to this line :
int GetRandomNumber = rnd.Next(1, arrOfWords.Length);
Thanks for the helpers!
rnd is null , add a line
rnd = new Random();
at the start of your event
rnd = new Random();
Instantiate rnd as above. You're using a null object that causes the exception in your question to be thrown.

Resources