Is this SQLite Update query correct? - sqlite

String query = "UPDATE CONTACT SET NAME ='" +
contact.getName()"',phoneNO='" +
contact.getContactNumber() +
"' WHERE ID = "+contact.getId();

"UPDATE CONTACT SET NAME ='" +
contact.getName() +
"',phoneNO='" +
contact.getContactNumber() +
"' WHERE ID = " +
contact.getId();
You are missing a "+" after the getName(). But this whole approach is risky because the name and other parameters could contain quotes or other characters that could cause the statement to be parsed incorrectly (SQL injection).
It is safer to embed the query string with named parameters instead.
Like
"UPDATE CONTACT SET NAME = #name, phoneNO - #phone WHERE ID = #ID"
Then you define the values for #name, #phone, and #ID when you execute. This is much safer. The exact details of how you do that depends on the database you are using and the API

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

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.

Asp.net add to database

Is it possible to add from a single textbox to different tables in a database.
I have a addclub webform and i would like to add clubname to a number of different tables.
The following is my current code that i have.
cmd = new SqlCommand("insert into youthclublist(youthclubname, description, address1, address2, county, postcode, email, phone) values ('" + youthclubname.Text + "', '" + description.Text + "','" + address1.Text + "','" + address2.Text + "', '" + county.Text + "', '" + postcode.Text + "', '" + email.Text + "', '" + phone.Text + "')", connection);
It is possible yes but consider my point below:
Think about normal form, it should be possible to design the database so that you only need to alter it on one place. If you have to change the name in several places it is likely not following normal form and the database could be redesigned.
The way you are doing the update is not advisable, have a look into SQLInjection attacks as the above code is vulnerable to this. Using parameters in the SQLCommand rather than creating a big string is a better way to do this from a security and performance point.
Hope I have not been too negative
Andy
You can do it if you use a transaction (and you should use parameters to get around some SQL injection attack problems) like so (this means that all the inserts are done in a single block on the database which is safer than doing them one after the other):
using (var cmd = new SqlCommand("BEGIN TRANSACTION;"
+ "INSERT INTO youthclublist(youthclubname) VALUES (#youthclubname);"
// Add all your INSERT statements here for the other tables in a similar way to above (I simplified it to show just one column, but you get the idea)
+ "COMMIT;", conn))
{
// Add your parameters - one for each of your text boxes
cmd.Parameters.Add("#youthclubname", SqlDbType.NVarChar).Value = youthclubname.Text;
// execute the transaction
cmd.ExecuteNonQuery();
}

Insert the date into table

I am trying to get From date and To date in two text boxes using the calender control and then trying to insert this value in a table. How can I proceed with this??
Please help..
string comstr = "insert into ATM_DETAILS_TB values(" + txtpin.Text + ",'" + Convert.ToDateTime(txtvldfrm.Text) + "','" + Convert.ToDateTime(txtvldto.Text) + "'," + Convert.ToInt32(ddlaccno.SelectedValue) + ",'" + Session["strUid"].ToString() + "')";
while using this code it shows error like "String was not recognized as a valid DateTime"
what should I do??
Use Validation controls to validate that the values in textbox values are valid dates.
Your code us contencating strings directly from user input. This opens you up to all sorts of nasty attacks, the primary being SQL Injection. Use parameterized queries instead.
Always use DateTime.TryParse or TryParseExact method to parse the date.
DateTime vldDate;
bool isValid=false;
if(DateTime.TryParse(txtvldfrm.Text,out vldDate))
{
isValid=true;
}
....
if(isValid)
{
command.Parametter.Add("#vldto",SqlDbType.DateTime).Value=vldDate;
command.Parametter.Add("#strUid",SqlDbType.VarChar,30).Value=Session["strUid"];
.....
}
You Use from parameterized queries like this:
string comstr = "insert into ATM_DETAILS_TB values(#pin,#vldfrm,#vldto,#ddlaccno,#strUid)";
YourCommand.Parametter.AddWithValue("#vldto",Convert.ToDateTime(txtvldto.Text));
YourCommand.Parametter.AddWithValue("#strUid",Session["strUid"].ToString());
....Define the Other Paraametter
Edit----
check this question String was not rec...

DataReader already open error when trying to run two queries

I have a couple of queries that I need to run one to a linked server and one not like this
Dim InvestorLookup As String = "DECLARE #investor varchar(10), #linkedserver varchar(25), #sql varchar(1000) "
InvestorLookup += "SELECT #investor = '" & investor & "', #linkedserver = '" & db & "', "
InvestorLookup += "#sql = 'SELECT * FROM OPENQUERY(' +#linkedserver + ', ''SELECT * FROM db WHERE investor = ' + #investor + ' '')' EXEC(#sql)"
Dim queryInvestorLookup As SqlCommand = New SqlCommand(InvestorLookup , conn)
Dim BondNoDR As SqlDataReader = queryInvestorLookup.ExecuteReader()
Dim PasswordCheck As String = "DECLARE #investor varchar(10), #password varchar(20), #linkedserver varchar(25), #sql varchar(1000) "
PasswordCheck += "SELECT #investor = '" + investor + "', #password = '" + password + "', #server = '" + db2 + "', "
PasswordCheck += "#sql = 'SELECT * FROM #server WHERE investor = #investor AND password = ' + #password + ' '' EXEC(#sql)"
Dim queryPasswordCheck As SqlCommand = New SqlCommand(PasswordCheck, conn)
Dim PasswordDR As SqlDataReader = queryPasswordCheck.ExecuteReader()
As far as I can tell from debugging the queries both run as they should but I get the error
There is already an open DataReader associated with this Command which must be closed first.
Is it possible to run two queries in two different DataReaders. I need to later reference each DataReader and select values from each.
By default it´s not possible to have two SqlDataReader's open at the same time sharing the same SqlConnection object. You should close the first one (queryInvestorLookup) before calling the second (queryPasswordCheck).
This would be good from a design and performance point of view since a recommendation for .NET is that every unmanaged resource (like database access) is opened as later as possible and closed early as possible.
Another way would be to enable MARS but afaik it is only available for Sql2005 and up.
The third solution would be to use the same SqlDataReader to issue the two queries and then navigate through then using NextResults() method.
If the provider that you are using supports it, you can enable MARS (Multiple Active Result Sets) by adding MultipleActiveResultSets=True to the connection string that you are using.
By default you can't have to dataReaders open on the same connection. So you could get one result, stuff it in a DataTable and then get the other result. Or you could turn on MARS
ADO.NET Multiple Active Resut Sets

Resources