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.
Related
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
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
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...
I am trying to verify if my SQL has been executed correctly, and if not return an error.
My code :
var db = Database.Open("database");
db.Execute("INSERT INTO Users(Username, Email, FirstName, SecondName) VALUES(?,?,?,?)", username, email, firstName, secondName);
Also, how can you mark a column as unique using WebMatrix? This seems to be a pretty basic functionality that I am really missing! I want to make it so that emails and usernames must be unique, but I cannot see any way to do this? I am essentially then hoping to test if the INSERT INTO can be executed (i.e there is no email/username the same already existing in the database).
Thank you for the help.
For your first question:
The Execute method returns the number of affected records, and your code snip is doing an insert so if it fails it'll return a value that isn't equal to 1.
var db = Database.Open("database");
if (db.Execute("INSERT INTO Users(Username, Email, FirstName, SecondName) VALUES(?,?,?,?)", username, email, firstName, secondName) < 1)
throw new Exception("Wasn't able to insert User record");
The second, I'm not sure about but it should probably be asked in a separate question.
I would create a stored procedure that conditionally adds the new user and returns a row count (0 if the user already exists):
create procedure dbo.AddUser
#username varchar(80)
, #email varchar(128)
, #firstname varchar(128)
, #secondname varchar(128)
as
insert into [Users] (Username,Email,FirstName,SecondName)
select #username, #email, #firstname, #secondname
where not exists(
select 1 from [Users] (nolock)
where Username=#username
and Email=#email
)
return ##rowcount
go
Calling from C#:
var db = Database.Open("database");
if (db.Execute("dbo.AddUser #username=?, #email=?, #firstname=?, #secondname=?", username, email, firstName, secondName) < 1)
throw new Exception("Wasn't able to insert User record");
I am trying to insert the user id from table users inside table session , field session_user, using textbox , but it seems it doesn't work ..
Here is my SQL code, I am using visual studio and trying to insert to a SQL Server table
SqlCommand addsession = new SqlCommand
("insert into dbo.session(session_user)
values (select user_id from dbo.users where username = '" + TextBox1.Text + "')",
badersql);
You shouldn't use the VALUES keyword when you're doing an INSERT ... SELECT:
insert into dbo.session (session_user) select user_id from dbo.users ...
If you are inserting the result of a query into another table, just leave out the VALUES keyword.
The VALUES keyword can always be replaced by a simple SELECT 'dummy', 'value' of the values you want to insert, but I suggest you still use VALUES whenever you want to make it clear that your results do not come from a query.
That being said, please use parameterized queries!! Imagine if someone were to enter the following text into TextBox1:
' or 1 = 1
What would happen?
To insert records from a query use this insert syntax:
insert into dbo.session (session_user)
select user_id from dbo.users where username = '" + TextBox1.Text + "'
You may want to do a select top 1 userid if you are expecting one row to be inserted like in the values statement.
i did it , the problem was that i can not name my record session_user , so i replaced with se_user and that solve the problem .
thank u all for ur help
so the correct sql statement is
insert into sessions (se_user) select USER_ID from users where username = '';