System.Data.SqlClient.SqlException: Incorrect syntax near '*' - asp.net

I'm trying to create session, using the following code:
SqlConnection conn = new SqlConnection("Data Source=THIRD-I;Initial Catalog=sessionlogin;Integrated Security=True;");
SqlDataAdapter sda = new SqlDataAdapter("Select (*) From logintable Where username='" + UserName.Text + "' and password='" + Password.Text + "'",conn);
DataTable dt = new DataTable();
sda.Fill(dt);
if (dt.Rows[0][0].ToString()== "1")
{
Session["user"] = UserName.Text;
Response.Redirect("welcome.aspx");
}

You need count of records from the data adapter. So the SQL query should be new SqlDataAdapter("Select count(*) From logintable Where username='" + UserName.Text + "' and password='" + Password.Text + "'",conn);

To fix an error:
Remove brackets from Select (*) or if you looking for total number add count
Must be select * or select count(*)
But your full code required big refactoring.
Disposing objects
Parameterize query
Assuming you take user input you should filter input

Related

error Incorrect syntax near ','

SqlConnection con = new SqlConnection(#"Data Source=shashi-PC\SQLEXPRESS;Initial Catalog=payroll;Integrated Security=True;Pooling=False");
SqlCommand com = new SqlCommand("insert into Leave_trans values(" + txtempid.Text + ",'" + ddlleavetype.SelectedValue + "'," + txtallowedays.Text + "," + txtpendingleave.Text + ",'" + txtleavefrom.Text + "','" + txtleaveto.Text + "'," + txttotalleaves.Text + ")");
com.Connection = con;
con.Open();
com.ExecuteNonQuery();
Response.Write("<script>alert('Leave data saved successfully')</script>");
con.Close();
This doesn't directly answer your question, but you should never take user-input and use string concatenation to build an SQL query (please take some time to read about SQL injection e.g. here or here).
Instead of concatenating the full query, you should use SqlParameter instances as placeholders for your values, e.g:
var com = new SqlCommand(
"insert into Leave_trans values(#empId, #leaveType, #allowedDays, ...)");
com.Parameters.Add(new SqlParameter("#empId", txtempid.Text));
com.Parameters.Add(new SqlParameter("#leaveType", ddlleavetype.SelectedValue));
com.Parameters.Add(new SqlParameter("#allowedDays", txtalloweddays.Text));
...
BTW: the cause for your problem is that you are not correctly single-quoting your inputs inside the query (e.g. txtempid.Text is not in single quotes). Using SqlParameters will also solve that problem for you.
I think the problem is in your query. You didn't provide us the data type of your database columns. But assuming from your query you are inserting some text from TextBox and one DropDownList selected item. From your TextBox text you will always get a string type value and for inserting string into your columns you should use single quotation '' before and after on it. But on your query you didn't use any quotation for some of your value parameter. I made an assumption and made a query for you. try this updated one.
SqlConnection con = new SqlConnection(#"Data Source=shashi-PC\SQLEXPRESS;Initial Catalog=payroll;Integrated Security=True;Pooling=False");
SqlCommand com = new SqlCommand("insert into Leave_trans values(" + "'" + txtempid.Text + "'", "'" + ddlleavetype.SelectedValue + "'","'" + txtallowedays.Text + "'","'" + txtpendingleave.Text + "'", "'" + txtleavefrom.Text + "'","'" + txtleaveto.Text + "'", "'" + txttotalleaves.Text + "')");
com.Connection = con;
con.Open();
com.ExecuteNonQuery();
Response.Write("<script>alert('Leave data saved successfully')</script>");
But i have some suggestion for you that is- you shouldn't use string as your table's primary key data type, it should be int type and another one is you should take int id of your selected item from your DropDownList not the text.

ASPX Long Selectcommand

I know this has to be posted somewhere and I'm probably not searching by the correct wording, but how do you break up a long selectcommand statement so you can see it all? Mine are running off the page and they're hard to read. Thanks in advance!
If you're using c#, you can do this like so:
SqlCommand sqlcmd = new SqlCommand("SELECT TopicsTitle,TopicContents,UserName,Avatar,NumberOfPost,uPoints,uType " +
"FROM Topic, Registration " +
"WHERE Topic.Category ='" + ilblTopic.Text + "'" +
"AND LastPostDate ='" + DateTime.Parse("...") + "'");
Bonus: please use a parameterized query.
You can use string builder to create a long strings.
System.Text.StringBuilder sb = new System.Text.StringBuilder();
sb.Append("SELECT field1, field2, field3 as Field3_Something,");
sb.Append(field4, field5, field6, field7, field8, field9");
sb.Append(FROM table JOIN table2 AS TNS ON TNS.id = table.id");
sb.Append(" WHERE something = 1");
SqlCommand sqlcmd = new SqlCommand(sb.ToString());

How to RETURN #Identity of instert data in spl in asp.net

I'm inserting data in a table with this code below.
SqlCommand cmd = new SqlCommand("INSERT INTO Users (Username,Password,FirstName,lastName,PhoneNumber,Address,City,State,Country,ZipCode,UserType,PayOut,TimeDate)"
+ ("VALUES ('" + TextBox1.Text + "','" + TextBox3.Text + "','" + TextBox4.Text + "','" + TextBox5.Text + "','" + TextBox6.Text + "','" + TextBox7.Text + "','" + TextBox8.Text + "','" + TextBox9.Text + "','" + TextBox10.Text + "','" + TextBox11.Text + "','User','0','" + Date + "')"), con);
cmd.ExecuteNonQuery();
I want to get Id of inserting Value in database which I save new data in table anyone have any idea what can i have to add in a code so i can RETURN #Identity of insert value in table and use that id some other code.
Thank you
First use parametrized queries (to avoid SQL Injection attack)
var sql = "INSERT INTO Users (Username,Password,FirstName,lastName,PhoneNumber,Address,City,State,Country,ZipCode,UserType,PayOut,TimeDate)" +
"values (#username, #password, #firstname, #lastname, #phone, #address, #city, #state, #country, #zipcode, #usertype, #payout, #timedate);" +
"select SCOPE_IDENTITY()";
var cmd = new SqlCommand(sql);
cmd.Parameters.AddWithValue("#username", TextBox1.Text);
cmd.Parameters.AddWithValue("#password", TextBox3.Text);
cmd.Parameters.AddWithValue("#firstname", TextBox4.Text);
cmd.Parameters.AddWithValue("#lastname", TextBox5.Text);
cmd.Parameters.AddWithValue("#phone" TextBox6.Text);
//and so on
var id = Convert.ToInt32(cmd.ExecuteScalar());
SCOPE_IDENTITY returns last id created for inserted row in given scope. This way you get back id. Use ExecuteScalar() method that returns one value from first row, first column.
Also do not store clear text as password, use some hashing method.
change your sql and code like as below
for sql 2005+
INSERT INTO Users (UserId,otherdata...)
OUTPUT INSERTED.ID
VALUES(#UserId, #othervalues...)
for sql 2000
INSERT INTO aspnet_GameProfiles(UserId,otherdata...)
VALUES(#UserId, #othervalues...);
SELECT SCOPE_IDENTITY()
And then
Int32 newId = (Int32) myCommand.ExecuteScalar();
Suggestion:
Make use of parameterize query to avoid sql injection attack....
The simplest way would be to append "SELECT SCOPE_IDENTITY()" to your SQL statement. You should parametrize your query to avoid SQL Injection, and it would look something like:
string sql = #"
INSERT INTO Users
(Username,Password,FirstName,lastName,PhoneNumber,
Address,City,State,Country,ZipCode,UserType,PayOut,TimeDate)
VALUES(#Username, #Password, ...)
SELECT SCOPE_IDENTITY()
";
SqlCommand cmd = new SqlCommand(sql, ...);
... append parameters ...
var identity = (decimal) cmd.ExecuteScalar();
If your identity column is an integer, you can either cast from decimal to integer, or do the cast in SQL Server, e.g.
string sql = #"
INSERT INTO Users
...
SELECT CAST(SCOPE_IDENTITY() AS INT)
";
SqlCommand cmd = new SqlCommand(sql, ...);
... append parameters ...
var identity = (int) cmd.ExecuteScalar();
Note that SCOPE_IDENTITY is generally a better choice than ##IDENTITY. In most cases, they will return the same value. But, for example, if your INSERT statement causes a trigger to fire, which inserts an identity value in a second table, then it's the identity value inserted into this second table that will be returned by ##IDENTITY. Using SCOPE_IDENTITY avoids this problem.

why is my insert not inserting a record in database

I am trying to insert a record into the database using the below method. I am calling this method in a button click event but for some reasons no record is being inserted.
There are four fields which need to be inserted: rpttemplateid - I am getting that field from another database table and all the other feilds are just static values.
What am i doing wrong below?
public void updatereporttemplate()
{
string cnn = WebConfigurationManager.ConnectionStrings["Underwriting"].ConnectionString;
SqlConnection cnn1 = new SqlConnection(cnn);
cnn1.Open();
string getrptdesc = "select max(rptdesc) + 1 from report_description where rptdesc < 999 and rptdesc is not null";
SqlCommand cmd = new SqlCommand(getrptdesc, cnn1);
SqlDataReader sdr = cmd.ExecuteReader();
sdr.Read();
int getcount = int.Parse(sdr[0].ToString());
sdr.Close();
string commandtext1 = "INSERT INTO report_template" + "(rpttemplateid,rpttemplatedescr,minsubs,minmebers) " +
" Values( " + getcount + "," + " " + " , " + 0 + "," + 0 + ")";
SqlCommand command1 = new SqlCommand
{
CommandText = commandtext1,
Connection = cnn1
};
You are missing command1.ExecuteNonQuery();
Also, have you considered using an IDENTITY column in your table instead of trying to manually set the count? What if that page is hit by multiple people at the same time?
You need to open the connection
cnn1.Open();
And then execute the command
command1.ExecuteNonQuery();

asp.net how to decrypt each label value in a gridview

i have an gridview that retrieves the data via a datatable like this:
protected DataTable allClients()
{
string conn, comm, tSub, tMain;
tSub = "client_sub";
tMain = "client_main";
conn = ConfigurationManager.ConnectionStrings["localsqlserver"].ConnectionString;
comm = "SELECT * FROM [" + tSub + "] t1 LEFT JOIN [" + tMain + "] t2 ON " +
"t1.customer_ID = t2.customer_ID";
SqlConnection connection = new SqlConnection(conn);
SqlCommand cmd = new SqlCommand(comm, connection);
connection.Open();
DataTable allTable = new DataTable();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(allTable);
connection.Close();
return allTable;
}
clientGrid.DataSource = allClients();
clientGrid.DataBind();
and its working fine on retrieving the data but the problem is i am trying to decrypt the value on retrieving it.
i used this encryptor class
so how can decrypt the value of each row in the gridview.
using asp.net 4.0, thanks
Two options - you can loop around the data table in your allClients() method before returning it, or you can look into handling the row bound events when you do the data bind on the grid view - this would allow you to access each row as its created in the grid view and manipulate the data displayed.

Resources