I am using MS Access as a database for a school project. The following is my query:
public static string qry4 = "update INTERNETSETTINGS set password = #password , url = #url , databasename = #databasename , port = #port , username = #username";
It is giving me the following error: Syntax Error in Update Statement
Command.Parameters.AddWithValue("#url", urlBox.Text.ToString());
Command.Parameters.AddWithValue("#databasename", databaseBox.Text.ToString());
Command.Parameters.AddWithValue("#port", portBox.Text.ToString());
Command.Parameters.AddWithValue("#username", userBox.Text.ToString());
Command.Parameters.AddWithValue("#password", passwordBox.Text.ToString());
It is making me angry because every thing is ok and right on target but still I am getting the error, but when I remove password from query it works fine. Please Help.
Most likely, password is a reserved keyword. Place it in braces...
update INTERNETSETTINGS set [password] = #password...
Related
I am creating a simple app where users create accounts. I want for the user to be able to change their password after making the account.
I am making this in C# using Oledb.
string test = "testing";
con.Open();
OleDbCommand command = new OleDbCommand();
command.Connection = con;
string query = "UPDATE tbl_users SET password = '" + test + "' WHERE username = '" + txtLoginUsername.Text + "'";
MessageBox.Show(query);
command.CommandText = query;
command.ExecuteNonQuery();
con.Close();
I keep getting the error:
" System.Data.OleDbException: 'Syntax error in UPDATE'"
This error is occuring in the line:
command.ExecuteNonQuery();
To clarify what Hossein has answered, when you are building your query command by adding strings together, you are wide-open to SQL-injection. Please read up on it some to protect your future development.
With reference to using "parameters". This is basically referring to a place-holder value for the query, like an "insert here" instead of you hard adding parts to the query like you were wrapping single quotes before and after the values for the password and user name.
Looking at your original query
"UPDATE tbl_users SET password = '" + test + "' WHERE username = '" + txtLoginUsername.Text + "'";
What if someone put in values of
Password: What's Up
Username: O'Conner
Your final query command when concatenated with your approach would create a value
UPDATE tbl_users SET password = 'What's Up' WHERE username = 'O'Conner'
See how the literal values have now screwed-up the string from its intent.
By using the "#" values, this is telling the SQL that hey... there will be another value coming along by the name provided, please use THAT value here. In some databases, they dont use named parameters, but "?" single character instead as a place-holder and you have to add the parameters in the exact order as they appear in the statement you are trying to prepare.
One other thing of personal preference. If your column name is UserName in I would use a parameter name like "#parmUserName" so you know it is EXPLICITLY the parameter and not accidentally just doing UserName = UserName and not get the results. A few more characters, but obvious what its purpose and where coming from works.
Now, how is that applied? Take a look again at Hossein's answer. Notice the two
command.Parameters.AddWithValue("#password", "test");
command.Parameters.AddWithValue("#username", txtLoginUsername.Text);
This is where the parameters are added to the command object. Stating, where you see the #password, use the following value I am putting here, same with #username.
Good luck going forward.
Use this syntax
Use bracket for password in query
because password is reserved word
link List of reserved world
using (var connection = new OleDbConnection("Your Connection String"))
{
var query = "UPDATE tbl_users SET [password] = #password WHERE username = #username";
using (var command = new OleDbCommand(query, connection))
{
connection.Open();
command.Parameters.AddWithValue("#password", "test");
command.Parameters.AddWithValue("#username", txtLoginUsername.Text);
command.ExecuteNonQuery();
}
}
I am trying to execute a query with a condition like if username already present then update the row, else insert username and password.
This is my code below:
using (SqlCommand cmd = new SqlCommand("INSERT INTO Users(Username,Password) VALUES(#User,#password) ON DUPLICATE KEY UPDATE Username=VALUES(Username), Password=VALUES(Password)"))
{
cmd.Connection = con;
cmd.Parameters.AddWithValue("#User", TextBox3.Text);
cmd.Parameters.AddWithValue("#password", Pwd);
con.Open();
cmd.ExecuteNonQuery();
}
I got the following error:
Incorrect syntax near the keyword 'ON'.
I am not able to figure out what is wrong in this. Can anyone please help me out?
In SQL Server you need to use a query something like this:
-- check if exists (by username) - if found, update password
IF EXISTS (SELECT * FROM dbo.Users WHERE Username = #User)
UPDATE dbo.Users
SET Password = #password
WHERE Username = #User
ELSE
INSERT INTO dbo.Users(Username, Password)
VALUES(#User, #password)
And as mentioned in my comments - do not use the .AddWithValue function (see linked blog post for details) but use this instead:
cmd.Parameters.Add("#User", SqlDbType.VarChar, 100).Value = TextBox3.Text;
And also, please do not store your passwords in clear text in the database!
It looks like you're using MySQL syntax. I don't think SQL Server has ON DUPLICATE KEY. You'd probably want a MERGE statement.
#marc_s
String query = #"IF EXISTS (SELECT * FROM Users WHERE Username = # User)
UPDATE Users
SET Password = #password
WHERE Username = # User
ELSE
INSERT INTO Users(Username, Password)
VALUES(# User, #password)";
using (SqlCommand cmd = new SqlCommand(query))
I used the code you gave and used to debug points to check if the code is executing ,and it was, still it is not updating or Inserting the values .I cant run the query in SQL server cause each time i open the query window VSudio restarts,i am using trial version of Visual Studio
I have designed a Log In System using C# where the username and password is checked in SQL server 2008 before loading the main page. I wish to encrypt the stored password on the database. Is it possible to do it using C# and SHA1 algorithm?
Following is my stored procedure:
ALTER procedure [dbo].[proc_UserLogin]
#userid varchar(20),
#password nvarchar(50)
As
declare
#ReturnVal varchar(500)
SET NOCOUNT ON
if exists(select userid,password from LoginManager where userid=#userid and password=#password)
set #ReturnVal='0|Logged in Successfully'
else
set #ReturnVal='1|Login Failed/Username does not exist'
select #ReturnVal
C# Code
public void button1_Click(object sender, EventArgs e)
{
mainform = new Form1();
string[] v;
OleDbConnection conn = new OleDbConnection("File Name=E:\\Vivek\\License Manager\\License Manager\\login.udl");
try
{
conn.Open();
string query = "EXEC dbo.proc_UserLogin'" + username.Text+ "', '" + password.Text+"'";
OleDbCommand cmd = new OleDbCommand(query, conn);
string s = Convert.ToString(cmd.ExecuteScalar());
v= s.Split('|');
if (v[0]=="0")
{
mainform.Show();
this.Hide();
}
else
{
MessageBox.Show("Please enter correct user credentials and try again");
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
conn.Close();
}
I have gone through similar questions asked by other users here, but they were not working for me. Can anyone suggest changes to the code, so that password encryption can be accomplished?
Thanks
Hash and salt passwords in C#
https://crackstation.net/hashing-security.htm
https://www.bentasker.co.uk/blog/security/201-why-you-should-be-asking-how-your-passwords-are-stored
As I stated in my comments, hashing passwords is something that you probably shouldn't be doing yourself.
A few things to note:
SHA1 is not recommended for passwords
Passwords should be salted
You should use a verified userstore framework rather than attempting to create your own, as you will likely "do it wrong"
I'm sure there are many more
That being said, to accomplish your specific question, you would want something like this:
Users
----
userId
passwordHashed
passwordHashed stores a hashed version of the user's password (the plain text password is never stored anywhere in persistence.)
for checking for valid password something like this is done:
ALTER procedure [dbo].[proc_UserLogin]
#userid varchar(20),
#password nvarchar(50)
As
declare
#ReturnVal varchar(500)
SET NOCOUNT ON
if exists(select userid,password from LoginManager where userid=#userid and password=HASHBYTES('SHA1', #password))
set #ReturnVal='0|Logged in Successfully'
else
set #ReturnVal='1|Login Failed/Username does not exist'
select #ReturnVal
For inserting/updating user passwords, you need to make sure to store the hashed password not the plain text password, as such;
INSERT INTO users(userId, passwordHashed)
VALUES (#userId, HASHBYTES('SHA1', #rawPassword)
or
UPDATE users
SET passwordHased = HASHBYTES('SHA1', #rawPassword)
WHERE userId = #userId
EDIT:
just realized you're asking how to accomplish the hash in C#, not SQL. You could perform the following (taken from Hashing with SHA1 Algorithm in C#):
public string Hash(byte [] temp)
{
using (SHA1Managed sha1 = new SHA1Managed())
{
var hash = sha1.ComputeHash(temp);
return Convert.ToBase64String(hash);
}
}
Your code snip could be:
conn.Open();
string query = "EXEC dbo.proc_UserLogin'" + username.Text+ "', '" + this.Hash(System.Text.Encoding.UTF8.GetBytes(password.Text))+"'";
OleDbCommand cmd = new OleDbCommand(query, conn);
You should also note that you should parameterize your parameters to your stored procedure rather than passing them in the manner you are - which it looks like you already have a separate question in regarding that.
I keep getting a syntax error when trying to run an update query in a SqlDataSource in asp.net.
UPDATE User
SET userName = #userName,
password = #password,
UserType = #UserType,
datejoined = #datejoined,
email = #email,
loggedIn = #loggedIn,
picFilePath = #picFilePath
WHERE
userName = #userName
All the tables are saved in a MS Access 2010 file and all the parameters are saved in session, but I don't think it's relevant since this is just a syntax error.
Any help would be appreciated.
User and password are MS Access reserved words, I'd suggest using square brackets for the table name and all of the column names:
UPDATE [User]
SET [userName] = #userName,
[password] = #password,
[UserType] = #UserType,
[datejoined] = #datejoined,
[email] = #email,
[loggedIn] = #loggedIn,
[picFilePath] = #picFilePath
WHERE
[userName] = #userName
Is there really a space in here?
loggedIn = # loggedIn
^
|
+---> should there be a space here?
I don't think there should be a space between the # and the loggedIn
In addition: in SQL Server, User is a reserved keyword - so in SQL Server, you need to use [User] for your table name instead. Not sure if that applies to MS Access, too.
In mysql i have set this SET sql_mode = 'ANSI';
my query is this:
select username, password from "user" where username = 'admin'
and password = 'password123'
and this query is getting successfully run in mysql and mssql.
But problem is I have problem in
Sqlcommand cmd=new Sqlcommand()
cmd.commanttext=:select username, password from "user" where username = 'admin'
and password = 'password123'";
and when i am using adp.fill(ds)
It is givin me error of sql syntax.
So how can i solve it.
Also remember that MYtable name is :=user
which is MSSQL and MYSQL reserved keyword.so how can i resolve this?
Use sql server with parameterized queries..
Sqlcommand cmd = new Sqlcommand();
cmd.CommandText = "select username, password from user where username = #admin and password = #pass";
cmd.Parameters.AddWithValue("#admin", "admin");
cmd.Parameters.AddWithValue("#pass", "password123");
If you are using SQL Server (as from the presence of a SqlCommand) then write:
Sqlcommand cmd = new Sqlcommand();
cmd.CommandText = "select username, password from " +
"[user] where username = 'admin' " +
"and password = 'password123'";
In Sql Server, to delimit reserved keywords, you use a couple of square brackets.
In MySql you use the backticks.
If you have a code that should work with both databases then you should look at this information from the property QuotePrefix and QuoteSuffix of the DbCommandBuilder base class and try to format correctly your query using the appropriate characters
MySqlCommandBuilder.QuotePrefix
SqlCommandBuilder.QuotePrefix