How to fix this syntax error? [closed] - syntax-error

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
this is my log in code. i am working on my dbms project. i have removed all the errors, as error list is showing 0 errors but when i m executing this, i m having this error at the top of my web page that Incorrect syntax near the keyword 'user'. and on remaining page there is my log in form appearing. i don't know how to fix this all. please let me know ASAP.
here is the code of log in form page.
protected void Button1_Click(object sender, EventArgs e)
{
try
{
//making necessary connections for linking database
SqlConnection conn = new SqlConnection("Data Source=BUSHRA-PC\\SQLEXPRESS;Initial Catalog=fb;Integrated Security=True");
conn.Open(); // openning connection
SqlCommand cmd = new SqlCommand("select * from user where Userid='" + TextBox1.Text + "'", conn);
//cmd.Connection = conn;
SqlDataReader dr = null;
dr = cmd.ExecuteReader();
if (dr.Read())
{
TextBox1.Text = dr["Userid"].ToString();
}
cmd.Connection = conn;
while (dr.Read())
{
Application["Userid"] = dr[0].ToString();
Application["Password"] = dr[1].ToString();
Application["Rollid"] = dr[2].ToString();
if (dr[0].ToString() == TextBox1.Text && dr[1].ToString() == TextBox3.Text)
{
if (Convert.ToInt16(dr[2].ToString()) == 2)
{
Response.Redirect("Admin.aspx");
}
else if (Convert.ToInt16((dr[2])) == 1)
{
Response.Redirect("StudentFB.aspx");
}
}
}
}
catch (Exception ex)
{
Response.Write(ex.Message); // if try fails display the error
}

user is a reserved keyword. Quote it, either with double quotes "user", or brackets [user].

Related

Can't use retrieved data from one query into another one?

I need to use a variable (edifcodigo) which assigned value is retrieved from one query to insert it in a table by using other query but there is a error that says this variable is not available in actual context. I'm kind of new in aspnet, could anybody know how to figure this out?
This is the code I have:
//Connect to db
string connetionString = #"myconexionstring";
string sql = "SELECT TOP 1 id_proyecto AS codigo FROM DNN_SCO_PROY_CO_PROYECTO_TBL WHERE nombre_proyecto= '"+ uedif +"'";
//find building code by querying the database
try
{
using (SqlConnection conexion = new SqlConnection(connetionString))
{
conexion.Open();
using (SqlCommand query = new SqlCommand(sql, conexion))
{
SqlDataReader result = query.ExecuteReader();
while (result.Read())
{
string edifcodigo = result["codigo"].ToString();
}
}
}
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
//Save referer friend
try
{
using (SqlConnection conn = new SqlConnection(connetionString))
{
conn.Open();
using (SqlCommand cmd = new SqlCommand("DNN_SVI_SCO_DATOS_RECOMIENDA_AMIGO_SP", conn))
{
cmd.CommandType = System.Data.CommandType.StoredProcedure;
cmd.Parameters.Add("#DRA_PROYECTO_CLIENTE", System.Data.SqlDbType.VarChar).Value = edifcodigo; ;
}
}
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
That's because you declared the variable inside a different code block. Every time you open a curly bracket, you open a new code block. Every time you close the curly bracket, you close the current code block. Each code block have it's own scope - it can access variables declared in the surrounding code block, but not variables declared in "sibling" code blocks.
Also, please read about parameterized queries and how they protect you from SQL injection, and change your queries accordingly.
Also, you don't need to close the connection between the two commands, and you can reuse a single command instance in this case. Here is an improved version of your code:
//Connect to db
var connetionString = #"myconexionstring";
var sql = "SELECT TOP 1 id_proyecto AS codigo FROM DNN_SCO_PROY_CO_PROYECTO_TBL WHERE nombre_proyecto = #nombre_proyecto";
//find building code by querying the database
try
{
using (var conexion = new SqlConnection(connetionString))
{
conexion.Open();
using (var cmd = new SqlCommand(sql, conexion))
{
cmd.Parameters.Add("#nombre_proyecto", SqlDbType.NVarChar).Value = uedif;
var edifcodigo = cmd.ExecuteScalar();
//Save referer friend
cmd.Parameters.Clear();
cmd.CommandText = "DNN_SVI_SCO_DATOS_RECOMIENDA_AMIGO_SP";
cmd.CommandType = System.Data.CommandType.StoredProcedure;
cmd.Parameters.Add("#DRA_PROYECTO_CLIENTE", System.Data.SqlDbType.VarChar).Value = edifcodigo; ;
}
}
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
You are declaring the string variable inside your while loop, it loses scope once you exit the while loop, move it's declaration above with:
string connetionString = #"myconexionstring";
string sql = "SELECT TOP 1 id_proyecto AS codigo FROM DNN_SCO_PROY_CO_PROYECTO_TBL WHERE nombre_proyecto= '"+ uedif +"'";
string edifcodigo = "";
You are trying to use a variable that declared in another scope. edifcodigo should be declared in the parent scope of both try blocks.
//Connect to db
string connetionString = #"myconexionstring";
string sql = "SELECT TOP 1 id_proyecto AS codigo FROM DNN_SCO_PROY_CO_PROYECTO_TBL WHERE nombre_proyecto= '"+ uedif +"'";
string edifcodigo=""; // YOU SHOULD DECLARE edifcodigo HERE
and than rest of code will come
//find building code by querying the database
try
{
using (SqlConnection conexion = new SqlConnection(connetionString))
{
conexion.Open();
using (SqlCommand query = new SqlCommand(sql, conexion))
{
SqlDataReader result = query.ExecuteReader();
while (result.Read())
{
edifcodigo = result["codigo"].ToString();
}
}
}
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
//Save referrer friend
try
{
using (SqlConnection conn = new SqlConnection(connetionString))
{
conn.Open();
using (SqlCommand cmd = new SqlCommand("DNN_SVI_SCO_DATOS_RECOMIENDA_AMIGO_SP", conn))
{
cmd.CommandType = System.Data.CommandType.StoredProcedure;
cmd.Parameters.Add("#DRA_PROYECTO_CLIENTE", System.Data.SqlDbType.VarChar).Value = edifcodigo; ;
}
}
}
catch (Exception ex)
{
Response.Write(ex.Message);
}

ADO.net Performing Multiple queries (ExecuteQuery & ExecuteScalar) and displaying the result in a web form control

Hey wish you all to have a happy holiday,
I am trying to display multiple query results from a SQL database table to a grid view control and a label. I have no problem with the grid view result, but the result from the ExecuteScalar command is not displaying inside my lable control with an ID="myCount". I could not figure out what went wrong with my code. I need your help.
protected void Page_Load(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["MBSDB"].ConnectionString);
try {
conn.Open();
string query="SELECT * FROM tblBook";
using (SqlCommand mycmd = new SqlCommand(query, conn)) {
myGrid.DataSource = mycmd.ExecuteReader();
myGrid.DataBind();
}
string query2 = "SELECT count(title) FROM tblBook";
using (SqlCommand mycmd2 = new SqlCommand(query2, conn)) {
int count = (int)mycmd2.ExecuteScalar();
myCount.Text = count.ToString();
}
}
catch {
Exception(e);
}
finally { conn.Close(); }
}
Are you sure about there is no error. I think, the error occured and handling in the catch block and you are unaware of it.
You should change it;
(int)mycmd2.ExecuteScalar();
to
Convert.ToInt32(mycmd2.ExecuteScalar());
You can't unboxing an object like this; (int)mycmd2.ExecuteScalar()

Items are listed in listbox, I want to use foreach to delete the items from SQL [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
private void SearchTable()
{
try
{
using (SqlConnection con = new SqlConnection("Data Source=localhost\\SQLEXPRESS;Initial Catalog=Steripack;Integrated Security=True"))
{
foreach (var item in lstCompleted.Items)
{
string killtag = item.ToString();
con.Open();
using (SqlCommand command = new SqlCommand("DELETE FROM tblAsset1 WHERE tagID = " + killtag))
{
command.ExecuteNonQuery();
lstCompleted.Items.Add("Removed: " + killtag);
}
con.Close();
}
}
}
catch (Exception ex)
{
lblStatus.Text = "SQL Failed..." + ex;
}
}
First, use sql-parameters instead of string concatenation. Otherwise you are open for sql-injection. You also have to assign the connection to the command.
However, there is another issue here: you are modifying the collection that you are enumerating in the foreach.
One way: use another collection where you store the items you'll add later:
using (SqlConnection con = new SqlConnection("Data Source=localhost\\SQLEXPRESS;Initial Catalog=Steripack;Integrated Security=True"))
{
List<string> deletedMessages = new List<string>();
foreach (object item in lstCompleted.Items)
{
int killtag = int.Parse(item.ToString());
con.Open();
using (SqlCommand command = new SqlCommand("DELETE FROM tblAsset1 WHERE tagID = #killtag", con))
{
command.Parameters.Add(new SqlParameter("#killtag", SqlDbType.Int).Value = killtag);
command.ExecuteNonQuery();
deletedMessages.Add("Removed: " + killtag);
}
//con.Close(); // unnecessary with using
}
foreach (string deletedMsg in deletedMessages)
lstCompleted.Items.Add(deletedMsg);
}
Another approach is to store the items that you want to delete in another collection which you enumerate in the foreach:
List<string> toDelete = lstCompleted.Items.Cast<string>().ToList();
foreach (string item in toDelete)
{
int killtag = int.Parse(item);
con.Open();
using (SqlCommand command = new SqlCommand("DELETE FROM tblAsset1 WHERE tagID = #killtag", con))
{
command.Parameters.Add(new SqlParameter("#killtag", SqlDbType.Int).Value = killtag);
command.ExecuteNonQuery();
lstCompleted.Items.Add("Removed: " + killtag);
}
}
Note that the .ToList() in the first line is essential since that creates a different, unassociated list which doesn't refer to the ObjectCollection in Listbox.Items.
Looks like you haven't assigned sqlcommand object to your connection
SqlCommand("DELETE FROM tblAsset1 WHERE tagID = " + killtag, Con)

Should I Close SQLConnection For All Transactions in Webservice?

I am using ASP.Net WebserviceApplication for my application and it is communicating with my SQL Server. Should I close SQLConnection after all user's sql transactions or it should be open everytime?
For example;
public void Connection()
{
if (connection == null)
connection = new SqlConnection(ConfigurationManager.ConnectionStrings["Conn"].ToString());
if (connection.State == ConnectionState.Closed)
connection.Open();
else if (connection.State == ConnectionState.Broken)
{
connection.Close();
connection.Open();
}
}
[WebMethod]
public long GetUsersRankMonthly(string userName)
{
Connection();
SqlCommand command = new SqlCommand("Select scores.Rank From (SELECT ROW_NUMBER() OVER(ORDER BY Score DESC) AS Rank,Score,NickName,ID FROM teatalay.TopScoresGeneral) scores Where UserName = #userName", connection);
command.Parameters.Add(new SqlParameter("#userName", userName));
var result = (long?)command.ExecuteScalar();
return result.HasValue ? result.Value : -1;
}
Thank you.
Wrap your transactions in a using statement when using a sql command. Let ASP.NET take care of SQL Connection pooling. It is a bit more refined at it than your code. Keep everything as condensed as possible and only modify if you notice that the number of connections to your server are what are the source of your performance issues.
Edit
using (var cnn = new SqlConnection("connection string here")){
using (var cmd = new SqlCommand("SProc or parametized text", cnn)){
cnn.Open();
// do stuff
cnn.Close();
}
}
In general when handling connections is better to use using moreover the block
if (connection.State == ConnectionState.Closed)
doesn't guarranty that it will open you the connection because you might be at ConnectionState.Connecting
The using statement guarantes it will close you connection when finished:
public long GetUsersRankMonthly(string userName)
{
connection = new SqlConnection(ConfigurationManager.ConnectionStrings["Conn"].ToString());
using (connenction)
{
connenction.Open();
SqlCommand command = new SqlCommand("Select scores.Rank From (SELECT ROW_NUMBER() OVER(ORDER BY Score DESC) AS Rank,Score,NickName,ID FROM teatalay.TopScoresGeneral) scores Where UserName = #userName", connection);
using (command)
{
..........
......
}
}
}

Retrieve SQL Statement Does Not Go Into While Loop

I am having problem when doing retrieve function in 3-tier in C#. Here is the codes:
public DistributionStandardPackingUnits getSPUDetail(string distributionID)
{
DistributionStandardPackingUnits SPUFound = new DistributionStandardPackingUnits();
using (var connection = new SqlConnection(FoodBankDB.connectionString))
{
SqlCommand command = new SqlCommand("SELECT name, description, quantity FROM dbo.DistributionStandardPackingUnits WHERE distribution = '" + distributionID + "'", connection);
connection.Open();
using (var dr = command.ExecuteReader())
{
while (dr.Read())
{
string name = dr["name"].ToString();
string description = dr["description"].ToString();
string quantity = dr["quantity"].ToString();
SPUFound = new DistributionStandardPackingUnits(name, description, quantity);
}
}
}
return SPUFound;
}
When I run in browser, it just won't show up any retrieved data. When I run in debugging mode, I realized that when it hits the while loop, instead of executing the dr.Read(), it simply just skip the entire while loop and return null values. I wonder what problem has caused this. I tested my query using the test query, it returns me something that I wanted so I think the problem does not lies at the Sql statement.
Thanks in advance.
Edited Portion
public static SqlDataReader executeReader(string query)
{
SqlDataReader result = null;
System.Diagnostics.Debug.WriteLine("FoodBankDB executeReader: " + query);
SqlConnection connection = new SqlConnection(connectionString);
SqlCommand command = new SqlCommand(query, connection);
connection.Open();
result = command.ExecuteReader();
connection.Close();
return result;
}