Refuses to make ExecuteNonQuery : Incorrect syntax near '(' - asp.net

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

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

Error: An expression of non-boolean type specified in a context where a condition is expected

I want to pass three query string variables, which ars DateFrom, DateTo and UserName. When I call that the variable, it shows an error:
'An expression of non-boolean type specified in a context where a condition is expected, near 'admin'.'".
How can I resolve the issue? Here is my code:
protected void Page_Load(object sender, EventArgs e)
{
strDate = Convert.ToDateTime(Request.QueryString["DateFrom"]);
endDate = Convert.ToDateTime(Request.QueryString["DateTo"]);
UserName = Convert.ToSingle(Request.QueryString["UsName"]);
string UserName = Request.QueryString["UsrName"];
string sql;
sql = ("SELECT * FROM tblReport WHERE Date between'" + strDate + "'and'" + endDate + "'and'" + UserName + "'");
SqlDataAdapter sda = new SqlDataAdapter(sql, con);
DataTable dt = new DataTable();
DataSet dst = new DataSet();
sda.Fill(dst, "tblReport");
crypt.Load(#"D:\My Project\Asp.Net\ITApplication\ITApplication\CrystalReport.rpt");
crypt.SetDataSource(dst);
CrystalReportViewer1.ReportSource = crypt;
}
you are missing something in your where clause... should be like this:
WHERE Date BETWEEN '<FromDate>' AND '<ToDate>'
AND UserName = '<UserName>'
Your SQL string is not formatted well.
Put spaces near yout and operators and use () in your between:
sql = ("SELECT * FROM tblReport WHERE [Date] between ('" + strDate + "' and '" + endDate + "') and UserName='" + UserName + "'");
Side note:
Using SQL strings with concatenating values like this is a very bad idea. It exposes you to SQL Injections, and overall a bad practice. Please consider using Command.Parameters:
SqlCommand Command = new SqlCommand("SELECT * FROM tblReport WHERE [Date] between (#strDate and #endDate) and UserName=#UserName");
Command.Parameters.Add(new SqlParameter("strDate", strDate));
Command.Parameters.Add(new SqlParameter("endDate", endDate));
Command.Parameters.Add(new SqlParameter("UserName", UserName));

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

Stored procedure doesn't return output

I have a simple stored procedure which inserts a users record in a table and should give out its userid.
Here is the stored procedure:
Alter proc spRegistration
#UserId nvarchar(10) output,
#Name nvarchar(20),
#EmailAdd nvarchar(20)
as
begin
Declare #Count int;
Declare #ReturnCode int
Select #Count = Count(EmailAdd)
from tblAllUsers
where EmailAdd = #EmailAdd
if #Count > 0
begin
Set #ReturnCode = -1
end
else
begin
Set #ReturnCode = 1
Insert into tblAllUsers(Name, EmailAdd)
values(#Name, #EmailAdd)
end
Select #UserId = UserId
from tblAllUsers
where EmailAdd = #EmailAdd
Select #ReturnCode as ReturnCode
end
I try to get the userid into a textbox like below :
string CS = ConfigurationManager.ConnectionStrings["hh"].ConnectionString;
using (SqlConnection con = new SqlConnection(CS))
{
con.Open();
SqlCommand cmd = new SqlCommand("spRegistration", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#Name", txtName.Text);
cmd.Parameters.AddWithValue("#EmailAdd", txtEmailAddress.Text);
var UserID = cmd.Parameters.AddWithValue("#UserId", SqlDbType.NVarChar);
UserID.Direction = ParameterDirection.Output;
int ReturnCode = (int)cmd.ExecuteScalar();
if (ReturnCode == -1)
{
lblRegMessage.Text = "This email has already been registered with us.";
}
else
{
lblRegMessage.Text = "You were registered successfully.";
txtUserId.Text=(String)UserID.Value;
}
The table as well as the stored procedure is far too complex,I have simplified it for better understanding of problem.UserId is Alphanumeric.Dont worry about that.
Putting a break point shows a null against var UserID
Where am i going wrong?
You need to Use .ToString() on UserID
txtUserId.Text= UserID.Value.ToString();
EDIT:
var UserID = cmd.Parameters.AddWithValue("#UserId", SqlDbType.NVarChar,50);

Why insert statement generates 2 rows?

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

Resources