I'm trying to create a registration page using C# on Visual Basic 2012. When I debug I get 0 errors, but when I try to register an account I get the following error.
"Incorrect syntax near ')'"
If I try to create an account with an existing username it says that username already exist. So I'm able to connect to the SQL server, but I'm not sure where I went wrong.
This registration page should create accounts in my DB DNMembership> Table> Accounts
Here is my code I'm working with.
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["RegDNMembershipConnectionString"].ConnectionString);
con.Open();
string insCmd = "Insert into Accounts (AccountName, Passphrase, EmailAddress, FullName, Country)";
SqlCommand insertUser = new SqlCommand(insCmd, con);
insertUser.Parameters.AddWithValue("#AccountName", TextBoxUN.Text);
insertUser.Parameters.AddWithValue("#Passphrase", TextBoxPass.Text);
insertUser.Parameters.AddWithValue("#EmailAddress", TextBoxEA.Text);
insertUser.Parameters.AddWithValue("#FullName", TextBoxFN.Text);
insertUser.Parameters.AddWithValue("#Country", DropDownListCountry.SelectedItem.ToString());
try
{
insertUser.ExecuteNonQuery();
con.Close();
Response.Redirect("Login.aspx");
}
catch(Exception er)
{
Response.Write("<b>Something Really Bad Happened... Please Try Again.< /br></b>");
Response.Write(er.Message);
}
What did I do wrong?
Looks like you forget to add VALUES part in your INSERT command.
VALUES
Introduces the list or lists of data values to be inserted. There must
be one data value for each column in column_list, if specified, or in
the table. The value list must be enclosed in parentheses.
Change your sql query like;
string insCmd = #"Insert into Accounts (AccountName, Passphrase, EmailAddress, FullName, Country)
VALUES(#AccountName, #Passphrase, #EmailAddress, #FullName, #Country)";
And use using statement to dispose your SqlConnection and SqlCommand like;
using(SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["RegDNMembershipConnectionString"].ConnectionString))
{
using(SqlCommand insertUser = new...)
{
//Your code..
}
}
You haven't specified any parameters in your SQL, or a VALUES section - you're saying "I want to insert into these fields..." but not what you want to insert. It should be something like:
string insCmd =
"Insert into Accounts (AccountName, Passphrase, EmailAddress, FullName, Country) "
+ "Values (#AccountName, #Passphrase, #EmailAddress, #FullName, #Country");
You need to change the SQL statement:
string insCmd = "Insert into Accounts (AccountName, Passphrase, EmailAddress, FullName, Country) VALUES (#AccountName,#Passphrase,#EmailAddress,#FullName,#Country)";
You are missing part of Insert statement
INSERT INTO table (col1, col2) VALUES (#col1, #col2)
Or if you want to insert all values into columns in order they are in table
INSERT INTO table VALUES (#col1, #col2)
There is several alternatives for INSERT command in SQL Server.
Specify COLUMNS and after that specify VALUES
SQL Syntax - INSERT INTO TABLE(AccountName, Passphrase, EmailAddress, FullName, Country)
VALUES ('AccountName', 'Passphrase', 'EmailAddress', 'FullName', 'Country')
C# string insCmd = "INSERT INTO TABLE(AccountName, Passphrase, EmailAddress, FullName, Country)
VALUES (#AccountName, #Passphrase, #EmailAddress, #FullName, #Country)"
If you are sure about the order of columns you can skip specifying columns, this can be risky in case you screw up order of VALUES you will insert values into wrong columns
SQL Sytanx - INSERT INTO TABLE VALUES ('AccountName', 'Passphrase', 'EmailAddress', 'FullName', 'Country')
C# string insCmd = "INSERT INTO TABLE VALUES (#AccountName, #Passphrase, #EmailAddress, #FullName, #Country)"
Good resources to read would be
W3School - http://www.w3schools.com/sql/sql_insert.asp
Technet - http://technet.microsoft.com/en-us/library/dd776381(v=sql.105).aspx
Alternative to INSERT INTO TABLE you can call stored procedures from C# that inserts into table. Use of stored procedures can help you reduce ad-hoc queries, help prevent SQL injection, reduce network traffic, add additional validation server side. Your code will look as follows.
SqlCommand cmd = new SqlCommand("usp_InsertIntoAccount", con);
con.Open();
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(new SqlParameter("#AccountName", TextBoxUN.Text));
cmd.Parameters.Add(new SqlParameter("#Passphrase", TextBoxPass.Text));
cmd.Parameters.Add(new SqlParameter("#EmailAddress", TextBoxEA.Text));
cmd.Parameters.Add(new SqlParameter("#FullName", TextBoxFN.Text));
cmd.Parameters.Add(new SqlParameter("#Country", DropDownListCountry.SelectedItem.ToString()));
try
{
cmd.ExecuteNonQuery();
con.Close();
Response.Redirect("Login.aspx");
}
catch(Exception er)
{
Response.Write("<b>Something Really Bad Happened... Please Try Again.< /br></b>");
Response.Write(er.Message);
}
Additional resources are listed on answer at the following questions How to execute a stored procedure within C# program
Related
So I'm trying to insert a new row into my database with SQLite3, and for some reason I'm getting a SQL logic error.
Database dbObject = new Database();
string query = "INSERT INTO info ('firstName, lastName, email') VALUES (#firstName, #lastName, #email";
SQLiteCommand myCommand = new SQLiteCommand(query, dbObject.Connection); //Opens chain of commands
dbObject.OpenConnection();
myCommand.Parameters.AddWithValue("#firsName", "blank name");
myCommand.Parameters.AddWithValue("#lastName", "blank last name");
myCommand.Parameters.AddWithValue("#email", "blank#gmail.com");
var result = myCommand.ExecuteNonQuery();
dbObject.CloseConnection();
Console.WriteLine("Rows added: {0}", result);
Console.ReadKey();
Can someone please tell me what am I doing wrong? Thank you!
Your query misses bracket at the end (after #email).
Moreover, I am not sure about the single quotes you added between firstName and email. I think they should be removed.
"INSERT INTO info (firstName, lastName, email) VALUES (#firstName, #lastName, #email)";
And as a side note that is not relevant to the error, you also need to dispose SQLiteCommand class as it is not disposed by itself. You can do it with using statement.
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 tried the following code to save to a database. The condition is are, I have a value in a dropdown list and the values are New= 1, and old=2. If the user selects 1 or new then it will save data to database or if they select old then it will show the exist data.
Now this time my label shows data inserted but the data is not saved to the table (But doesn't show any error).
protected void btnsave_Click(object sender, EventArgs e)
{
if (ddl.Text=="1")
{
cs.Open();
string query = "insert into resig (#id,#name,#email) values('"+txtgn.Text+"','"+txtgname.Text+"','"+txtsg.Text+"')";
SqlCommand cmd = new SqlCommand(query,cs);
lbdmsg.Text = "Data Inserted";
//txtgname.Text = ddl.SelectedItem.ToString();
}
else
{
cs.Open();
string query = "select name, email from resig where id='" + txtgn + "'";
SqlCommand cmd= new SqlCommand(query,cs);
dr =cmd.ExecuteReader();
while(dr.Read())
{
string name= txtgname.Text;
string email=txtsg.Text;
}
cs.Close();
}
}
I see 2 things;
You are try to parameterize your column names, not your values.
You are not executing your insert command with ExecuteNonQuery().
You should use parameterized queries. This kind of string concatenations are open for SQL Injection attacks.
For example;
if (ddl.Text == "1")
{
string query = "insert into resig (id,name,email) values(#id, #name, #email)";
SqlCommand cmd = new SqlCommand(query,cs);
cmd.Parameters.AddWithValue("#id", txtgn.Text);
cmd.Parameters.AddWithValue("#name", txtgname.Text);
cmd.Parameters.AddWithValue("#email", txtsg.Text);
cs.Open();
cmd.ExecuteNonQuery();
}
Call cmd.ExecuteNonQuery() to run the command on your db
Your SQL is both wrong, and very dangerous/susceptible to SQL injection. The first list in parenthesis must be a column list, and the values list should be parameters to avoid SQL injection:
string query = "insert into resig (id, name, email) values(#id, #name, #email)";
SqlCommand cmd = new SqlCommand(query, cs);
cmd.Parameters.Add(new SqlParameter("#id", txtgn.Text));
cmd.Parameters.Add(new SqlParameter("#name", txtgname.Text));
cmd.Parameters.Add(new SqlParameter("#email", txtsg.Text));
cmd.ExecuteNonQuery();
You should parameterize the select statement as well. Why is this important? Consider the resulting SQL if the user entered this for id and selected old:
'; delete resig; --
Building SQL by concatenating user input opens your database to the whim of users with bad intentions, and in this day and age should never be used. Countless web sites have been defaced and had their data corrupted -- it was ill-considered back in the day, but now we know better, and there's no excuse.
I have the statement in c# :
String sql = String.Format("UPDATE Table SET FIRST_NAME='{0}',LAST_NAME='{1}',BIRTH_DATE='{2}' where CUSTOMER_NUMBER ='{3}'",FirstName, LastName,DateOfBirth,Number);
The above statement doesn't execute if the first name,last name etc have apostrophe like O'Hare,O'Callahagan because of this the update statement gets the wrong syntax.
How to escape the apostrophe in string.format?
How to escape the apostrophe in string.format?
Don't escape it, use parameterized query instead.
Imagine a user with a really unconventional name strongly resembling SQL statements for dropping a table or doing something equally malicious. Escaping quotes is not going to be of much help.
Use this query instead:
String sql = #"UPDATE Table
SET FIRST_NAME=#FirstName
, LAST_NAME=#LastName
, BIRTH_DATE=#BirthDate
WHERE CUSTOMER_NUMBER =#CustomerNumber";
After that, set values of FirstName, LastName, DateOfBirth, and Number on the corresponding parameters:
SqlCommand command = new SqlCommand(sql, conn);
command.Parameters.AddWithValue("#FirstName", FirstName);
command.Parameters.AddWithValue("#LastName", LastName);
command.Parameters.AddWithValue("#BirthDate", BirthDate);
command.Parameters.AddWithValue("#CustomerNumber", CustomerNumber);
Your RDMBS driver will do everything else for you, protecting you from malicious exploits. As an added benefit, it would let you avoid issues when the date format of your RDBMS is different from your computer: since your date would no longer be passed as a string representation, there would be no issues understanding which part of the formatted date represents a day, and which one represents a month.
You should use parameterized queries:
using (SqlCommand cmd = new SqlCommand("UPDATE Table SET FIRST_NAME= #FirstName, LAST_NAME= #LastName, BIRTH_DATE=#BirthDate where CUSTOMER_NUMBER = #CustomerNumber"))
{
cmd.Parameters.Add(new SqlParameter("FirstName", FirstName));
cmd.Parameters.Add(new SqlParameter("LastName", LastName));
cmd.Parameters.Add(new SqlParameter("BirthDate", DateOfBirth));
cmd.Parameters.Add(new SqlParameter("CustomerNumber", Number));
// Now, update your database
} // the SqlCommand gets disposed, because you use the 'using' statement
By using parameterized queries, you solve your problem. Using parameterized queries has two other advantages:
Protection against SQL Injection
Readability
Use parameterized query.
string commandString = "insert into MyTable values (#val1, #val2)";
SqlCommand command = new SqlCommand(commandString, connection);
command.Parameters.AddWithValue("val1", "O'Hare");
command.Parameters.AddWithValue("val2", "O'Callahagan");
command.ExecuteNonQuery();
I am getting an error msg of "syntax error" for the INSERT INTO command when it gets to cmd.ExecuteNonQuery.
It is important that I use string.Format, and that the structure stays as close to the current structure as possible.
{
OleDbConnection con = DAL.GetConnection();
con.Open();
if (con.State == ConnectionState.Open)
{
string s = string.Format("INSERT INTO DataTable1 (Username, Password, FName, LName, Bdate, Sex, City, Mail) VALUES ('{0}', '{1}', '{2}', '{3}', #{4}#, {5}, {6}, '{7}')", uname, pass, fname, lname, bd, sex, city, mail);
OleDbCommand cmd = DAL.GetCommand(con, s);
int check = cmd.ExecuteNonQuery();
if (check == 0)
{
con.Close();
Response.Redirect("Reg.aspx?err=-An error has occured. Please try again-");
}
Thank you.
Probably you have some quotes in the passed text, try using parameters ...
string s = "INSERT INTO DataTable1 (Username) VALUES (#user)";
OleDbCommand cmd = DAL.GetCommand(con, s);
//Add the parameter ...
OleDbParameter nam = new OleDbParameter("#user",uname);
cmd.Parameters.Add(nam);
Check out OleDbCommand.Parameters if you haven't already. It is safer (along the lines of #Mark B's comment), and it will probably clear up the syntax error you have.
If you insist on a pure String.Format approach, simply output cmd.CommandText for debugging to see where the syntax error lies.