ASP.NET SqlConnection - Exception - Incorrect Syntax - asp.net

I have the following code and this runs I get an SqlException error saying invalid syntax near the keyword 'User'. Any ideas? Guessing it's something simple but I just can't spot it.
string insertStmt =
"INSERT INTO User (UserName) VALUES(#UserName)";
using (SqlConnection _con = new SqlConnection(myConnectionString))
using (SqlCommand _cmd = new SqlCommand(insertStmt, _con))
{
_cmd.Parameters.Add("#UserName", SqlDbType.NVarChar).Value = UserName;
try
{
_con.Open();
_cmd.ExecuteNonQuery();
_con.Close();
}
catch (Exception x)
{
// output exception
}
}

You need to escape user probably since it's a reserved word in sql.
Try this
string insertStmt =
"INSERT INTO [User] (UserName) VALUES(#UserName)";

Related

There is already an open DataReader associated with this Commands which must be closed first

It keep giving me
There is already an open DataReader associated with this Command which must be closed first.
What is exactly wrong with my database code, can somebody help me?
protected void Button1_Click1(object sender, EventArgs e)
{
SqlConnection connect = new SqlConnection(ConfigurationManager.ConnectionStrings
["RegistrationConnectionString"].ConnectionString);
connect.Open();
string insertQuery = #"IF NOT EXISTS(SELECT 1 FROM Registration where Username=#Uname) insert into Registration (Username,Password,Phone,Email,Country) values (#Uname ,#Password ,#Phone ,#Email ,#Country)";
SqlCommand command = new SqlCommand(insertQuery, connect);
command.Parameters.AddWithValue("#Uname", name.Text);
command.Parameters.AddWithValue("#Phone", Phone.Text);
command.Parameters.AddWithValue("#Email", Email.Text);
command.Parameters.AddWithValue("#Password", Password.Text);
command.Parameters.AddWithValue("#Country", Country.SelectedItem.ToString());
SqlDataReader sdr = command.ExecuteReader();
if (sdr.HasRows)
{
Response.Write("Username already exisited!");
}
else
{
Response.Write("User name is available!");
}
command.ExecuteNonQuery();
connect.Close();
Try this code
using (SqlConnection connect = new SqlConnection(ConfigurationManager.ConnectionStrings
["RegistrationConnectionString"].ConnectionString))
{
connect.Open();
string insertQuery = #"IF NOT EXISTS(SELECT 1 FROM Registration where Username=#Uname) insert into Registration (Username,Password,Phone,Email,Country) values (#Uname ,#Password ,#Phone ,#Email ,#Country)";
using (SqlCommand command = new SqlCommand(insertQuery, connect))
{
command.Parameters.AddWithValue("#Uname", name.Text);
command.Parameters.AddWithValue("#Phone", Phone.Text);
command.Parameters.AddWithValue("#Email", Email.Text);
command.Parameters.AddWithValue("#Password", Password.Text);
command.Parameters.AddWithValue("#Country", Country.SelectedItem.ToString());
if (command.ExecuteNonQuery() > 0)
{
Response.Write("User name is available!");
}
else
{
Response.Write("Username already exisited!");
}
}
}
You are calling SqlCommand twice when call ExecuteReader and when call ExecuteNonQuery. Due to your statement never returns records to client Property HasRows will be always false. And last it is recomended always use using statement when instantiating disposable object.

creating sql connection object once and using it several times

i'm creating login and register page in MVC asp.net but problem is that for each purpose i have to do all SQl connection, command, try open etc which really makes it slow so i as wondering that if i can get rid of creating ti again and again and just create sqlconnection thing once and calling it again and again for login, registration etc
namespace LoginSys.Models
{
public class database
{
public ConnectionStatus connectDB(String name, String email, String pwd, String conStr)
{
// var con = conStr;
SqlConnection sqlCon = new SqlConnection(conStr);
SqlCommand sqlCom = new SqlCommand();
sqlCom.Connection = sqlCon;
sqlCom.CommandText = "insert into tblRegister (userName, userEmail, userPwd) values (#name, #email, #pwd)";
sqlCom.Parameters.AddWithValue("#name", name);
sqlCom.Parameters.AddWithValue("#email", email);
sqlCom.Parameters.AddWithValue("#pwd", pwd);
ConnectionStatus connectStatus = new ConnectionStatus();
int row_aff;
try
{
sqlCon.Open();
row_aff = sqlCom.ExecuteNonQuery();
connectStatus.Message = "OK";
}
catch(Exception ex)
{
connectStatus.Message = ex.Message;
}
finally
{
sqlCon.Close();
}
return connectStatus;
}
}
}
Actually you are not creating a new physical connection to the database. ADO.NET uses a connection pool. This means that even if you create a new instance of SqlConnection, you are not actually creating a new physical connection but are drawing one from the pool. Also when you call the .Close() method you are not actually closing the underlying connection. You are just returning it to the connection pool so that it can be reused.
So your code won't be slow because of that.
The only improvement I may recommend you to this code is to wrap the IDisposable objects in using statements:
public ConnectionStatus ConnectDB(string name, string email, string pwd, string conStr)
{
using (SqlConnection sqlCon = new SqlConnection(conStr))
using (SqlCommand sqlCom = sqlCon.CreateCommand())
{
sqlCon.Open();
sqlCom.CommandText = "insert into tblRegister (userName, userEmail, userPwd) values (#name, #email, #pwd)";
sqlCom.Parameters.AddWithValue("#name", name);
sqlCom.Parameters.AddWithValue("#email", email);
sqlCom.Parameters.AddWithValue("#pwd", pwd);
ConnectionStatus connectStatus = new ConnectionStatus();
try
{
sqlCom.ExecuteNonQuery();
connectStatus.Message = "OK";
}
catch(Exception ex)
{
connectStatus.Message = ex.Message;
}
return connectStatus;
}
}

Unable to evaluate expression because the code is optimized or a native frame is on top of the call stack when I use scope identity

Here is ehat I try to do
on button_click I read the values from the text boxes and insert them in them in the database.
as tourist number for example maybe two or three tourists with ExecuteScalar; i get the ids of teh tourists which are inserted!
public void cmdInsert_OnClick(object sender, EventArgs e)
{
if (Page.IsValid)
{
string numtourist = (string)Session["tourist_number"];
for (int i = 0; i < Int32.Parse(numtourist); i++)
{
TextBox tx888 = (TextBox)FindControl("txtNameK" + i.ToString());
TextBox tx888_1 = (TextBox)FindControl("txtMidNameK" + i.ToString());
TextBox tx888_2 = (TextBox)FindControl("txtLastNameK" + i.ToString());
string insertSQL = "INSERT INTO Tourist (Excursion_ID, Excursion_date_ID, Name_kir,Midname_kir, Lastname_kir)";
insertSQL += " VALUES (#Excursion_ID, #Excursion_date_ID, #Name_kir,#Midname_kir, #Lastname_kir) SELECT ##IDENTITY";
string connectionString = "Data Source = localhost\\SQLExpress;Initial Catalog=excursion;Integrated Security=SSPI";
SqlConnection con = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand(insertSQL, con);
cmd.Parameters.AddWithValue("#Excursion_ID", Convert.ToInt32(mynew2));
cmd.Parameters.AddWithValue("#Excursion_date_ID", Convert.ToInt32(mynewnewstring));
cmd.Parameters.AddWithValue("#Name_kir", tx888.Text);
cmd.Parameters.AddWithValue("#MidName_kir", tx888_1.Text);
cmd.Parameters.AddWithValue("#LastName_kir", tx888_2.Text);
int added;
try
{
con.Open();
added = (int)cmd.ExecuteScalar();
lblproba.Text = "";
Tourist.Add(added);
lblproba.Text += Tourist.Count();
}
catch (Exception ex)
{
lblproba.Text += ex.Message;
}
finally
{
con.Close();
}
}
createReservation();
}
}
I call CreateReservationFunction AND i CREATE A NEW RESERVAION WITH THE ID OF THE USER WHO HAS MADE THE RESERVATION. wITH SELECT IDENTITY I TRY TO GET THE RESERVATION_ID of the reservation and here I get the exception "Unable to evaluate expression because the code is optimized or a native frame is on top of the call stack". So I wonder can this exception has something commn with the fact that in my solution exceptthe asp.net web projectI got library class in which I has .edmx file The entity framework model of my database and in my last form I don't use Ado,net but Entity framework
public void createReservation()
{
string insertSQL = "Insert INTO RESERVATIONS (User_ID) values (#User_ID) SELECT ##IDENTITY";
string connectionString = "Data Source = localhost\\SQLExpress;Initial Catalog=excursion;Integrated Security=SSPI";
SqlConnection con = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand(insertSQL, con);
cmd.Parameters.AddWithValue("#User_ID", 9);
try
{
con.Open();
string added = cmd.ExecuteScalar().ToString();
createTouristReservation(added);
}
catch (Exception ex)
{
lblproba.Text+= ex.Message;
}
}
Don't use ##IDENTITY but SCOPE_IDENTITY and add a semicolon between the insert and the select.
string insertSQL = #"INSERT INTO Tourist (Excursion_ID, Excursion_date_ID, Name_kir,Midname_kir, Lastname_kir)
VALUES (#Excursion_ID, #Excursion_date_ID, #Name_kir,#Midname_kir, #Lastname_kir)
;SELECT CAST(scope_identity() AS int)";

One or more errors occurred during processing of command. ORA-00936: missing expression

i am trying to perform insert but getting this error:
[Exception: One or more errors occurred during processing of command.
ORA-00936: missing expression]
it works for select query.
table structure is as follow
database-oracle 10g
table name-investor_info
investor_id-number
first_name-varchar
lastname-varchar
age-number
location-varchar
contact_number-varchar
email-varchar
checked-number-number
public void insert_details(string fname,string lname, int age, string location, string contactnumber, string email)
{
int id = get_id()+1;
int check=0;
string query = "INSERT INTO INVESTOR_INFO (INVESTOR_ID,FIRST_NAME,LAST_NAME,AGE,LOCATION,CONTACT_NUMBER,EMAIL,CHECKED) VALUES (#val1,#val2,#val3,#val4,#val5,#val6,#val7,#val8);";
try
{
conn.Open();
OleDbCommand command1 = new OleDbCommand(query,conn);
command1.Parameters.AddWithValue("#val1", id);
command1.Parameters.AddWithValue("#val2", fname);
command1.Parameters.AddWithValue("#val3", lname);
command1.Parameters.AddWithValue("#val4", age);
command1.Parameters.AddWithValue("#val5", location);
command1.Parameters.AddWithValue("#val6", contactnumber);
command1.Parameters.AddWithValue("#val7", email);
command1.Parameters.AddWithValue("#val8", check);
command1.CommandType = CommandType.Text;
command1.ExecuteNonQuery();
// conn.Close();
}
catch (Exception e)
{
throw new Exception(e.Message);
}
finally
{
conn.Close();
}
}//end of insert
Remove the semicolon in string QUERY
it should be
string query = "INSERT INTO INVESTOR_INFO (INVESTOR_ID,FIRST_NAME,LAST_NAME,AGE,LOCATION,CONTACT_NUMBER,EMAIL,CHECKED) VALUES (#val1,#val2,#val3,#val4,#val5,#val6,#val7,#val8)";
Remove semicolon from the string query and try like below,
string query = "INSERT INTO INVESTOR_INFO (INVESTOR_ID,FIRST_NAME,LAST_NAME,AGE,LOCATION,CONTACT_NUMBER,EMAIL,CHECKED) VALUES (#val1,#val2,#val3,#val4,#val5,#val6,#val7,#val8)";
Always specific the schema name with table name.(schemeName.tableName)
I have not worked on Oracle for a while, but have you tried replacing the # with a : for the parameters. Refer to the following artice:
http://msdn.microsoft.com/en-us/library/system.data.oracleclient.oraclecommand.parameters.aspx

Multipart Identifier "arafa.almahmud08#gmail.com" couldnot be bound

I have built a custom validator,
I have a sql query like this:
protected void custom_serverValidate(object sender, ServerValidateEventArgs e)
{
connect();
string strSQL = "select EmailAddress from Accounts_Users where EmailAddress=" + REmailTextBox.Text;
SqlCommand cmd = new SqlCommand(strSQL, objConnection);
if (e.Value.ToString() == cmd.ExecuteScalar().ToString())
{
e.IsValid = false;
}
else
e.IsValid = true;
disConnect();
}
when I execute my code in the browser and an email address and submit it , I get the error mentioned in the title. how to fix it ?
You are missing quotes around your email address. However - this is a SQL injection attack waiting to happen. Please switch to using a parameter.
string strSQL = "select EmailAddress from Accounts_Users where EmailAddress = #EmailAddress"
...
cmd.Parameters.AddWithValue("#EmailAddress", REmailTextBox.Text);
You forgot to use the single quotes. Use:
string commandText = "select EmailAddress from Accounts_Users where EmailAddress=#EmailAttress";
SqlCommand cmd = new SqlCommand(commandText, conn);
cmd.Parameters.Add("#EmailAddress", REmailTextBox.Text);

Resources