How to save "NULL" instead of spaces in SQL Server? - asp.net

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 + "', ''), ..)";

Related

'Parameters supplied for object 'AdminAssistant' which is not a function. If the parameters are intended as a table hint, a WITH keyword is required.'

While inserting values into the database i am getting error which is said in subject dont know what i am missing.
string ImagePath = "";
string str = "insert into AdminAssistant() values('"+TextBox7.Text+ "','" + TextBox1.Text + "','" + TextBox2.Text + "','" + TextBox5.Text + "','" + TextBox6.Text + "','" + DropDownList2.Text + "','" + TextBox4.Text + "','" + DropDownList1.Text+ "','" + TextBox9.Text + "','"+ImagePath+"','"+DateTime.Now+"','Active')";
SqlCommand cmd = new SqlCommand(str,con);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
Label1.Text = "Admin Created Successfully.....!!!";
Below is the Query
Create Table AdminAssistant
(
A_ID int identity(1,1) not null primary key,
Aname varchar(20),
Aphone varchar(16),
Amail varchar(20),
A_Address varchar(150),
A_City varchar(20),
A_Gender varchar(10)NOT NULL CHECK (A_Gender IN('Male', 'Female')),
A_Password varchar(20),
Aroll varchar(20)NOT NULL CHECK (Aroll IN('SuperAdmin', 'Admin')),
MetaDescription varchar(256),
Media varchar(40),
RegisterDate datetime,
A_Status varchar(20)NOT NULL CHECK (A_Status IN('Active', 'Disable'))
)
I think this values should inserted into database despite that it is giving error.
The error is probably caused by the presence of the parenthesys after the name of the table, but this is a simple fix to do.
Your real problem lies in the string concatenation for your values.
This is a no-no in the sql world because it could be the source of many parsing bugs (for example, the presence of a single quote in the values could break the syntax and DateTime.Now is converted to a string following rules the not always are understood by the sql parser engine).
But most important is the possibility of Sql Injection.
Here some links to start your discovery for this big security risk
How can I explain Sql Injection without technical jargon.
How does the SQL injection from the “Bobby Tables” XKCD comic work?
So the only fix is through a parameterized query.
string str = "insert into AdminAssistant
(Aname,Aphone,Amail,A_Address,A_City,A_Gender,A_Password,
Aroll,MetaDescription,Media,RegisterDate,A_Status)
values(#name,#phone,#mail,#address,#city,#gender,#pass
#roll,#descr,#media,#regdata,'Active')";
using(SqlConnection con = new SqlConnection(......))
using(SqlCommand cmd = new SqlCommand(str, con))
{
con.Open();
cmd.Parameters.Add("#name", SqlDbType.NVarChar).Value = TextBox7.Text;
... other varchar parameters
cmd.Parameters.Add("#regdataq", SqlDbType.DateTime).Value = DateTime.Now;
... complete the parameters collection
cmd.ExecuteNonQuery();
}
And, I have forget to talk about storing passwords in clear text into a database. This is another very important consideration for your security. Here another link with useful info
Best way to store password in database

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

Updating Password in sql database using text-box

using ASP.NET & VB.NET i trying to update the user password, where it is equals to the sessionID
Database using is SQL Local.
here is the vb .net code
Dim pass As String
pass = tboxConFirmPass.Text
Dim connce As SqlCeConnection = New SqlCeConnection(ConfigurationManager.ConnectionStrings("ConnectionString").ToString())
connce.Open() 'make the connection to DB
Dim sqlCommand As String = "UPDATE [tbCustomer] SET [Password] = ('" _
+ tboxConFirmPass.Text + "', '" + "WHERE [CustomerID] = #CustomerID" + "')"
Dim cmd As SqlCeCommand = New SqlCeCommand(sqlCommand, connce)
cmd.ExecuteNonQuery()
connce.Close()
MsgBox("Your Password has been chaged.")
End Sub
here is the SqlDataSource
UpdateCommand="UPDATE [tbCustomer] SET [Password] = #Password WHERE [CustomerID] = #CustomerID">
Error = There was an error parsing the query. [ Token line number = 1,Token line offset = 42,Token in error = , ]
Right, your query needs to be changed thus:
Dim sqlCommand As String = "UPDATE [tbCustomer] SET [Password] = '" _
& Replace(tboxConFirmPass.Text, "'", "''") & "' WHERE [CustomerID] = #CustomerID"
I've sorted your brackets and quotes mismatches out, changed the string concatenation operator to & and put an escape in to reduce the possibility of SQL injection vulnerability (if someone puts a single quote in their password, your query will no longer fall over, or worse).
To set a value for #CustomerID you need to add a SQL Parameter to the command object. If you don't give it a value you'll get the error mentioned in your comment. Alternatively you can concatenate the value like you do with the password:
Dim sqlCommand As String = "UPDATE [tbCustomer] SET [Password] = '" _
& Replace(tboxConFirmPass.Text, "'", "''") & "' WHERE [CustomerID] = " & CustomerID
Note that you will need to use a variable that is initialised with the ID of the customer whose password is being changed.

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