ASPX Long Selectcommand - asp.net

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

Related

System.Data.SqlClient.SqlException: Incorrect syntax near '*'

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

How to save "NULL" instead of spaces in SQL Server?

It's pretty simple I have some textboxes to fill up and submit to SQL Server, some of them may be blank, so whenever I run the query, I get a bunch of spaces instead of the word Null in the database..
My query goes like :
var qry = "INSERT INTO tablename (Text,Trans, ..)
Values ('"TextBox1.text "','" TextBox2.text, ..)";
db.Query(qry);
A better option would be to do something like....
SqlCommand cmd = new SqlCommand("INSERT INTO tablename (Text,Trans) Values (#Text, #Trans)");
cmd.Parameters.Add(new SqlParameter("#Text" , string.IsNullOrEmpty(TextBox1.text) ? (object)DBNull.Value : TextBox1.text);
cmd.Parameters.Add(new SqlParameter("#Trans", string.IsNullOrEmpty(TextBox2.text) ? (object)DBNull.Value : TextBox2.text);
You can use NULLIF:
INSERT INTO tablename (Text,Trans, ..)
Values (NULLIF('" + TextBox1.text + "', ''), NULLIF('" + TextBox2.text + "', ''), ..)";

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.

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.

Insert into SQL Server table gives me nothing

Very frustrating one... I have tried many combinations of ', " and so on but my insert command just refreshing the page.
What am I doing wrong?
Simple two text fields form with button. Under button I have this:
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["przychodniaConnectionString1"].ConnectionString);
con.Open();
string cmdStr = "INSERT INTO specyfik(speNazwa, speIlosc) values ('" + speNazwa.Text + "', '" + speIlosc.Text + "')";
SqlCommand insertCmd = new SqlCommand(cmdStr, con);
con.Close();
Zero errors while compiling and when testing, it seems like refreshed page. Nothing appears in db.
Don't you need to call insertCmd.ExecuteNonQuery() ?
...
SqlCommand insertCmd = new SqlCommand(cmdStr, con);
int row_affected = insertCmd.ExecuteNonQuery();
...
You need to execute your SqlCommand:
insertCmd.ExecuteNonQuery();
Also, you should look into parameterizing that query:
http://www.codinghorror.com/blog/2005/04/give-me-parameterized-sql-or-give-me-death.html
Will you like to make more improvements in your code using stored Proc and improvemnet in your code behind file ? Take a look at this answer...
https://stackoverflow.com/a/9595501/1209450

Resources