once again giving the syntax error for insert into query - c#

string connectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\\Samples\\login.mdb";
string uname, pass;
uname = textBox1.Text;
pass = textBox2.Text;
OleDbConnection myConnection = new OleDbConnection(connectionString);
myConnection.Open();
string query = "insert into LOGIN_TABLE (UserName, Password) VALUES ('" + textBox1.Text.ToString() + "','" + textBox2.Text.ToString() + "') ";
OleDbCommand myCommand = new OleDbCommand(query, myConnection);
//myCommand.CommandText = query;
OleDbParameter myParm = myCommand.Parameters.Add("#uname", OleDbType.VarChar, 50);
myParm.Value = textBox1.Text;
myParm = myCommand.Parameters.Add("#pass", OleDbType.VarChar, 50);
myParm.Value = textBox2.Text;
myCommand.ExecuteNonQuery();
myConnection.Close();

From the docs for OleDbCommand.Parameters:
The OLE DB .NET Provider does not
support named parameters for passing
parameters to an SQL statement or a
stored procedure called by an
OleDbCommand when CommandType is set
to Text. In this case, the question
mark (?) placeholder must be used.
There's an example on the same page.
However, you're not even using parameters in your SQL query. You're inviting a SQL injection attack by embedding the user input directly into the SQL and then also adding parameters.
Your query should just be:
String query = "insert into LOGIN_TABLE (UserName, Password) VALUES (?, ?)";
It looks like you can still give parameters names, even if they're not used - so just the change above may be enough.
EDIT: Is it possible that UserName or Password are reserved names? Try escaping them - I know in SQL Server it would be [UserName], [Password] but I don't know if that's true in Access. What happens if you try to execute the same SQL in Access, by the way?

The data you are passing as parameters might have single-quotes, ', in it.
Try this textBox2.Text.Replace("'","''") when assigning values to the parameters.
One more thing, it is not necessary to use parameters when handling simple texts and numbers in simple queries.

Your query should be like this.
string query = "insert into LOGIN_TABLE (UserName, Password) VALUES ( #uname, #pass )";
Now after that write your code, and everything will be work for you.
Whenever you are reading value from textbox, use Trim() as textBox.Text.Trim().
Sorry it will be working for SqlConnection.
Thanks

Related

execute sql command in asp.net

I have a problem with executing a sql command to the DB. The command should add a new user to the 'users' table.
But when I run the code, I get this Exception on:
command.ExecuteNonQuery();
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.Data.OleDb.OleDbException: Syntax error in INSERT INTO statement.
this is the code of the page - GetSignIn.cshtml :
#{
string Uname = Request["name"];
string userName = Request["userName"];
string pass = Request["passWord"];
string pic = Request["pic"];
string privacy = Request["privacy"];
if(pic == null)
{
pic = "Shared/defaultPic.jpg";
}
System.Data.OleDb.OleDbConnection connection = new System.Data.OleDb.OleDbConnection();
connection.ConnectionString = #"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\Etay\Documents\Visual Studio 2012\WebSites\Josef\Shared\users.mdb";
try
{
System.Data.OleDb.OleDbCommand command = new System.Data.OleDb.OleDbCommand();
command.Connection = connection;
connection.Open();
command.CommandText = "INSERT INTO users (userName,passWord,Uname,pic) VALUES ('" + userName + "', '" + pass + "', '" + Uname + "', '" + pass + "', " + pic + ")";
command.ExecuteNonQuery();
Response.Redirect("../HtmlPage.html");
}
finally
{
connection.Close();
}
}
What should I change in my code? Why is it happening? Where is the syntax error in the INSERT INTO?
Use parameterized queries. Here is your statement rewritten to make use of them.
I replaced your try/finally with a using block although your try/finally was acceptable.
Parameterized queries prevent errors and Sql Injection Attacks. An error could occur in your existing code if I were to submit a tick as a part of my user name or password. In the current form this would result in an exception. This is because the tick character is used to quote strings in sql syntax.
using (System.Data.OleDb.OleDbConnection connection = new System.Data.OleDb.OleDbConnection())
{
connection.ConnectionString = #"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\Etay\Documents\Visual Studio 2012\WebSites\Josef\Shared\users.mdb";
using (System.Data.OleDb.OleDbCommand command = new System.Data.OleDb.OleDbCommand())
{
command.Connection = connection;
command.CommandText = "INSERT INTO users (userName,passWord,Uname,pic) VALUES (?,?,?,?)";
command.Parameters.Add(userName);
command.Parameters.Add(pass);
command.Parameters.Add(Uname);
command.Parameters.Add(pic);
connection.Open();
command.ExecuteNonQuery();
}
}
About parameters for an OleDb connection from OleDbCommand.Parameters
Remarks
The OLE DB .NET Provider does not support named parameters for passing parameters to an SQL statement or a stored procedure called by an OleDbCommand when CommandType is set to Text. In this case, the question mark (?) placeholder must be used. For example:
SELECT * FROM Customers WHERE CustomerID = ?
Therefore, the order in which OleDbParameter objects are added to the OleDbParameterCollection must directly correspond to the position of the question mark placeholder for the parameter in the command text.
What should I change in my code?
Change to parameters (that also fixes the problem that you don;t have quotes around the pic value)
Remove the second instance of pass in your values
command.CommandText = "INSERT INTO users (userName,passWord,Uname,pic) VALUES (#userName, #pass, #Uname, #pic)";
command.Parameters.Add("#userName").Value = userName;
.. etc.
It's unclear what the type if pic is - you are passing a string but I can;t tell of the column stores a file path or if you are indending to serialize the file and store it in a pinary field.
You set 4 fields after the "INTO" clause, however you're passing 5 parameters:
"INSERT INTO users (userName,passWord,Uname,pic) VALUES ('" + userName + "', '" + pass + "', '" + Uname + "', '" + pass + "', " + pic + ")";
Just add the fifth field, or remove one parameter from the VALUES part
Please check take a look at your Insert statement, it looks like that you provided password value twice.
The number of query values and the destination fields should be same in an INSERT statement.
You have the wrong number parameters in your insert statement. For clarity, why not use string.Format to keep everything uniform? (Assuming these are all string types)
var rawSql = #"Insert INTO Users (userName,passWord,Uname,pic) VALUES ('{0}','{1}','{2}','{3}')";
command.CommandText = string.Format(rawSql, userName, pass, Uname, pic);
command.ExecuteNonQuery();
However, it also looks like you probably want to include that 5th parameter as well - just extend the format :
var rawSql = #"Insert INTO Users (userName,passWord,Uname,pic, privacy) VALUES ('{0}','{1}','{2}','{3}','{4}')";
command.CommandText = string.Format(rawSql, userName, pass, Uname, pic, privacy);
command.ExecuteNonQuery();
Since most of the answers failed to address the SQL Injection vulnerability, here's an example with parameterized queries. In addition to preventing SQL Injection attacks, it also makes it easier to troubleshoot these types of issues, and you don't need to worry about quoting or not quoting parameters.
System.Data.OleDb.OleDbConnection connection = new System.Data.OleDb.OleDbConnection();
connection.ConnectionString = #"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\Etay\Documents\Visual Studio 2012\WebSites\Josef\Shared\users.mdb";
try
{
System.Data.OleDb.OleDbCommand command = new System.Data.OleDb.OleDbCommand();
command.Connection = connection;
connection.Open();
command.CommandText = "INSERT INTO users (userName, passWord, Uname, pic, privacy) VALUES (?, ?, ?, ?, ?)";
command.Parameters.Add(userName);
command.Parameters.Add(pass);
command.Parameters.Add(name);
command.Parameters.Add(pic);
command.Parameters.Add(privacy);
command.ExecuteNonQuery();
Response.Redirect("../HtmlPage.html");
}
finally
{
connection.Close();
}
Tnx 4 the help
It happend to be a problem with the database - you can not apply a INSERT INTO statement where the column name is "password". "password" is a Reserved word
in SQL.
Tnx again,
Etay

How does JET OLEDB Parameters compare strings with text field in and Access DB

I have the following update query in C# using a JET OLEDB connection, connecting to a ms access DB file. The query fails to change the fields, it runs correctly but just 0 rows changed.
I think the problem is how parameters are processed and compared against the DB but have no idea how to fix it.
The "User" column is set as text. I have an insert statement that works perfectly set up in the same fashion with the parameters.
com.CommandText = "UPDATE [ExamMaster] SET [User] = (DLookup('LName', 'Users', 'ID' = '#correctUser') WHERE [User] = '#user'";
com.Parameters.AddWithValue("#correctUser", correctUser);
com.Parameters.AddWithValue("#user", userName);
If I do not use a parameter for the where clause and just insert it into the command string like so:
WHERE [User] = '"+userName+"'";</code>
it will update the DB just fine. What am I missing here?
UPDATE:
With or with single quotes makes no difference and rearranging the order of the parameters does not work either.
The order matters. I "think" in your query user is being called first before the correctUser due to the DLOOKUP function.
com.Parameters.AddWithValue("#user", userName);
com.Parameters.AddWithValue("#correctUser", correctUser);
You don't need to single quote parameters:
WHERE [User] = #user";
and I'll guess that the DLOOKUP doesn't need the single quotes either, just [brackets] if the field name has a space or is a reserved word (which [User] might be).
You will need to change that a bit, try:
OleDbConnection cn = new OleDbConnection(aconnectionstring);
cn.Open();
//testing
int correctUser = 1;
string userName = "1";
OleDbCommand com = new OleDbCommand();
com.Connection = cn;
//You cannot have a parameter in DLookUp
com.CommandText = "UPDATE [ExamMaster] SET [User] = " +
"DLookup('LName', 'Users', 'ID = " + correctUser + "') WHERE [User] = #user";
com.Parameters.AddWithValue("#user", userName);
//You must execute the query
com.ExecuteNonQuery();

insert into sql db a string that contain special character '

i want to insert to a sql table a string that might contain ' character.
what is my best way to do so ?
should i insert a \ before the ' ?
here's my command in a c# code:
SqlCommand myCommand = new SqlCommand(
String.Format(
"insert into ACTIVE.dbo.Workspaces_WsToRefile values({0},'{1}',getdate())",
folderId,
NewWorkspaceName),
myConnection);
where NewWorkspaceName might contain ' character, so the insert will cause an exception at the moment.
thanks in advanced, hadas.
You should be using SqlParameter. http://msdn.microsoft.com/en-us/library/yy6y35y8.aspx
string query = "insert into ACTIVE.dbo.Workspaces_WsToRefile values(#folderID, #newWorkSpace, #createDate)";
using(SqlCommand cmd = new SqlCommand(query, SqlConnection))
{
SqlParameter param = new SqlParameter("#folderID", folderId);
param.SqlDbType = SqlDbType.Int;
cmd.Parameters.Add(param);
.....
}
You have only one option, forget everything else. Use Parametrized queries like this
SqlCommand myCommand = new SqlCommand("insert into ACTIVE.dbo.Workspaces_WsToRefile" +
" values(#id, #space, getDate()", myConnection);
myCommand.Parameters.AddWithValue("#id", folderId);
myCommand.Parameters.AddWithValue("#space", NewWorkspaceName);
myCommand.ExecuteNonQuery();
folderID and NewWorkspaceName, are passed to the Sql Engine inside parameters.
This will take care of special characters like quotes.
But you gain another benefit using parametrized queries. You avoid Sql Injection Attacks
NewWorkspaceName= NewWorkspaceName.Replace("\'","\'\'");
'' is a ' in sql
You can try this:
string stringToDatabase=Server.HtmlEncode("կҤїАͻBsdҤїА");
This saves 'stringToDatabase' in your database
. Then while retreiving
string OriginalText=Server.HtmlDecode(stringFromDatabase);

How do I insert data into MS Access file using SQL?

I am having a problem with inserting new data into MS Access 2007 file. It say I am having an incorrect SQL statement.
What is the problem here? I am not good at SQL. Please point out my error.
try
{
// Open database connection.
objOleDbConnection.Open();
objOleDbCommand.CommandText =
"INSERT INTO PersonalData (Type, UserName, Password) VALUES ('" + cmbType.Text + "','" + txtUserName.Text + "','" + txtPassword.Text + "')";
// Execute creating table command.
objOleDbCommand.ExecuteNonQuery();
}
To start with, you need to put quotes around your text data:
#"INSERT INTO PersonalData (Type, UserName, Password) VALUES (" + cmbType.SelectedIndex + ",'" + txtUserName.Text + "','" + txtPassword.Text + "')";
However, you would be much better off converting this to use parameters, since you won't have to worry about embedded quotes:
objOleDbCommand.CommandText = #"INSERT INTO PersonalData (Type, UserName, Password) VALUES (?, ?, ?)";
objOleDbCommand.Parameters.Add("Type", cmbType.SelectedIndex);
objOleDbCommand.Parameters.Add("UserName", txtUserName.Text);
objOleDbCommand.Parameters.Add("Password", txtPassword.Text);
Both Type and Password are reserved words. See Problem names and reserved words in Access.
If you must keep those as the field names, surround them with square brackets in your INSERT statement so the database engine will know to interpret them as fields:
"INSERT INTO PersonalData ([Type], UserName, [Password]) VALUES ...
On that same web page, follow the link for Database Issue Checker Utility. That utility can warn you about problems with reserved words in your application, and other potential troublesome issues.
Edit: If PersonalData includes additional fields which are required and do not have default values assigned, you must include those fields with values in your INSERT statement, or it will definitely fail.
Let's say txtUserName.Text is Foo, and txtPassword.Text is bar. Then you're getting
INSERT INTO PersonalData (Type, UserName, Password) VALUES (3,foo,bar)
instead of the syntactically correct
INSERT INTO PersonalData (Type, UserName, Password) VALUES (3,'foo','bar')
Since you don't have columns foo and bar, you are getting an error - is my assumption. Things get worse if you have baz,moo instead of foo. Or, gods forbid, Bobby Tables.
There a few places where you might encounter problems here.
Type, Username, and Password are all (I think) MS Access keywords. While they seem to work when used within Access istself (like in the Querybuilder, for example), they seem to throw exceptions when used from Client Code. Surround the fieldnames in your SQL Statement with square brackets, so that Access treats them as literals.
I strongly recommend using SQL Parameters for your in-line SQL, and then using ADO.NET Parameters to set the values. Google "SQL Injection Attack" to learn why. Plus, it's just good practive (there are some limited exceptions).
EDIT: Note that with OleDb, the parameters must appear in the same order as the fliednames in the list. THis is not the case with ADO & SQLClient. With Access, however, having your parameters out of order will create difficult-to-find problems . . .
Your SQL would then look like this:
INSERT INTO ([Type], [Username], [Password]) VALUES ( #Type, #UserName, #Password )
And your code might resemble THIS (I took some liberties here . . .
private void InsertUserData(int Type, String UserName, String Password)
{
// The "Using" block handles object creation and disposal -
// handy for unmanaged resources like database connections:
using(OleDbConnection cn = new OleDbConnection(YourConnectionString))
{
using(OleDbCommand cmd = new OleDbCommand())
{
cmd.Connection = cn;
// 1. Note the use of Parameters here. This will hinder attempts to
// compromise your app with SQl Injection and/or faulty user input.
// 2. Also note that, since "Type", "Username", and "Password" are all
// MS Access keywords, there is a potential for problems when
// used as fieldnames. Therefore we enclose them
// in square brackets [] in the "INSERT INTO" Clause:
String SQL =
"INSERT INTO PersonalData([Type], [UserName], [Password]) " +
"VALUES(#Type, #UserName, #Password)";
// Set the CommandText Proprty:
cmd.CommandText = SQL;
// Now create some OleDb Parameters:
OleDbParameter prmType = new OleDbParameter("#Type", Type);
OleDbParameter prmUserName = new OleDbParameter("#UserName", UserName);
OleDbParameter prmPassword = new OleDbParameter("#Password", Password);
// Add the params to the parameters collection:
cmd.Parameters.Add(prmType);
cmd.Parameters.Add(prmUserName);
cmd.Parameters.Add(prmPassword);
try
{
cn.Open();
cmd.ExecuteNonQuery();
cn.Close();
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
}
Hope that helps . . .

SQL INSERT - Invalid column name

As some of you may of seen from my previous post I'm new to using C# to create websites (Although I have a fair bit of experience using it for Windows Forms apps). The powers that be are tempting me away from PHP but I keep failing at what I consider the basics.
Anyway, this is my issue. I am trying to create a simple entry into a SQL database. I know my connection to the DB is fine as I can reel off SELECT queries all day long but I'm having trouble with using Insert.
Heres my code:
string filename = "abc123.jpg";
SqlConnection link = new SqlConnection(//you dont need to see my data here ;));
string sqlcode = "INSERT INTO file_uploads (upload_filename VALUES ("+filename+")";
SqlCommand sql = new SqlCommand(sqlcode,link);
link.open();
sql.ExecuteNonQuery();
This results in "Invalid column name abc123.jpg" returned from the try/catch.
Any help would be appreciated. (I wish they would let me do this in PHP lol!)
Thanks,
Tripbrock
You are missing a parenthesis after the column name and the value represents a string and as such must be enclosed in quotes:
string sqlcode = "INSERT INTO file_uploads (upload_filename) " +
"VALUES ('"+filename+"')";
However, the correct way would be to use a parameterized query:
string filename = "abc123.jpg";
SqlConnection link = new SqlConnection(/*you dont need to see my data here ;)*/);
string sqlcode = "INSERT INTO file_uploads (upload_filename) VALUES (#filename)";
SqlCommand sql = new SqlCommand(sqlcode,link);
sql.Parameters.AddWithValue("#filename", filename);
link.open();
sql.ExecuteNonQuery();
your SQL is bad formatted. Try this :
string sqlcode = "INSERT INTO file_uploads (upload_filename) VALUES ('"+filename+"')";
Where upload_filename is a name of the column
Really you should be parameterising your queries - this reduces the risk of injection attacks:
string filename = "abc123.jpg";
using( SqlConnection link = new SqlConnection(/*...*/;)) )
{
// sql statement with parameter
string sqlcode = "INSERT INTO file_uploads (upload_filename) VALUES (#filename)";
using( SqlCommand sql = new SqlCommand(sqlcode,link) )
{
// add filename parameter
sql.Parameters.AddWithValue("filename", filename);
link.open();
sql.ExecuteNonQuery();
}
}
Also note the using statements - these make sure that the connection and command objects are disposed of.
Try
string sqlcode = "INSERT INTO file_uploads (upload_filename) VALUES ('"+filename+"')";
You were missing a closing parentheses.
Don't know if it is a typo but the line should be:
string sqlcode = "INSERT INTO file_uploads (upload_filename) VALUES ('"+filename+"')";
Notice the ) after upload_filename.
Also also added the single quotes around the filename.
But you probably want to use a parameterized query:
string sqlcode = "INSERT INTO file_uploads (upload_filename) VALUES (#filename)";
Then use command.Parameters to add the actual value.
looks like you are missing a bracket:
string sqlcode = "INSERT INTO file_uploads (upload_filename VALUES ("+filename+")";
Should be
string sqlcode = "INSERT INTO file_uploads (upload_filename) VALUES ('"+filename+"')";
Also, to avoid SQL injection attacks you can use the SQLCommand objects like so.
using (SQLCommand oSQLCommand = new SQLCommand("INSERT INTO file_uploads (upload_filename) VALUES ( #FileName )")
{
oSQLCommand.Parameters.AddWithValue("#FileName", filename);
oSQLCommand.ExecuteNonQuery();
}

Categories

Resources