SQL CE Insert Query works only outside of C# - c#

I am trying to insert a row in my User table (SQL Server Compact 3.5). This is my query (LastName, FirstName and UserPassword are NVARCHAR, IsActive is BIT):
INSERT INTO Users (LastName, FirstName, IsActive, UserPassword) VALUES ('J', 'R', 1, 'T')
I converted this to the following code block in C#:
string returnQuery = "INSERT INTO Users (LastName, FirstName, IsActive, UserPassword)"
+ "VALUES(" + "'" + "#LastName" + "', '" + "#FirstName" + "', #IsActive" + ",'" + "#UserPassword" + "'";
SqlCeCommand returnQueryCommand =
new SqlCeCommand(returnQuery, connection) { CommandType = CommandType.Text };
returnQueryCommand.Parameters.AddWithValue("#LastName", newUser.LastName);
returnQueryCommand.Parameters.AddWithValue("#FirstName", newUser.FirstName);
returnQueryCommand.Parameters.AddWithValue("#IsActive", newUser.IsActive);
returnQueryCommand.Parameters.AddWithValue("#UserPassword", newUser.UserPassword);
I get a parsing error when running my code. However, when I run the query straight through CompactView, the row gets inserted just fine.
I am executed the query in another method (I am returning SqlCeCommand from this method).
Thoughts?

missing close bracket after values

your given code seems to be missing a closing parenthesis to close "VALUES" data.
string returnQuery = "INSERT INTO Users (LastName, FirstName, IsActive, UserPassword)" + "VALUES(" + "'" + "#LastName" + "', '" + "#FirstName" + "', #IsActive" + ",'" + "#UserPassword" + "')";

Related

Syntax error in INSERT INTO statement MS access (not keyword issue)

I am facing this error when I try to insert a data row in to table in ms access file.
dataTable is table I got using select * from TableName,
I got it, displayed it, made changes, now I want to replace previous one with new one. So I am going to delete all previous rows and add each row one by one from new table. But I am not able to insert any row.
I am getting this error
"Syntax error in INSERT INTO statement."
String query = "INSERT INTO [" + TableName + "] (TaskID, HTMLTopic, [Group], nKey,"
+ " nText, nImage, nSelImage, nFontName, nFontInfo, Keywords) VALUES (#TaskID,"
+ " #HTMLTopic, #Group, #nKey, #nText, #nImage, #nSelImage, #nFontName, "
+ " #nFontInfo, #Keywords)";
OleDbCommand command = new OleDbCommand(query, mdbConnection);
command.Parameters.AddWithValue("#TaskID", dataTable.Rows[0]["TaskID"]);
command.Parameters.AddWithValue("#HTMLTopic", dataTable.Rows[0]["HTMLTopic"]);
command.Parameters.AddWithValue("#Group", dataTable.Rows[0]["Group"]);
command.Parameters.AddWithValue("#nKey", dataTable.Rows[0]["nKey"]);
command.Parameters.AddWithValue("#nText", dataTable.Rows[0]["nText"]);
command.Parameters.AddWithValue("#nImage", dataTable.Rows[0]["nImage"]);
command.Parameters.AddWithValue("#nSelImage", dataTable.Rows[0]["nSelImage"]);
command.Parameters.AddWithValue("#nFontName", dataTable.Rows[0]["nFontName"]);
command.Parameters.AddWithValue("#nFontInfo", dataTable.Rows[0]["nFontInfo"]);
command.Parameters.AddWithValue("#Keywords", dataTable.Rows[0]["Keywords"]);
mdbConnection.Open();
command.ExecuteNonQuery();
mdbConnection.Close();
Edit:
Changed it just for debugging to
String query = "INSERT INTO [" + TableName + "] (TaskID, HTMLTopic, nRelative, [Group], nKey,"
+ " nText, nImage, nSelImage, nFontName, nFontInfo, Keywords) VALUES ('" + dataTable.Rows[0]["TaskID"]
+ "', '" + dataTable.Rows[0]["HTMLTopic"] + "', '" + dataTable.Rows[0]["nRelative"] + "', '" + dataTable.Rows[0]["Group"]
+ "', " + dataTable.Rows[0]["nKey"] + ", '" + dataTable.Rows[0]["nText"] + "', '" + dataTable.Rows[0]["nImage"]
+ "', '" + dataTable.Rows[0]["nSelImage"] + "', '" + dataTable.Rows[0]["nFontName"] + "', '" + dataTable.Rows[0]["nFontInfo"]
+ "', '" + dataTable.Rows[0]["Keywords"] + "')";
OleDbCommand command = new OleDbCommand(query, mdbConnection);
Debug.Print(command.CommandText);
mdbConnection.Open();
command.ExecuteNonQuery();
mdbConnection.Close();
I added some single quotes so database can understand them as string.
There looks to be a bug somewhere between the provider and the engine. It looks like the issue is with your column named nText.
I duplicated your schema in an Access 2013 db and received the same error that you did. I then started making various changes to the column names and the query. When I changed column names (appending a X to the end of each column) the INSERT worked. I then went back and started adding square brackets to other columns names. As soon as I did that for nText it worked. This query works for me in a C# console app using the Microsoft.ACE.OLEDB.12.0 oldeb provider:
String query =
"INSERT INTO [" + TableName + "] (TaskID,HTMLTopic,[Group],nKey,[nText],nImage,nSelImage,nFontName,nFontInfo,Keywords)" +
"VALUES" +
"(#TaskID,#HTMLTopic, #Group, #nKey, #nText, #nImage, #nSelImage, #nFontName,#nFontInfo, #Keywords)"
I agree with you that it shouldn't be a keyword / reserved word issue, but it sure acts like it is. NTEXT is a keyword in TSQL (SQL Server), but not Access according to https://support.microsoft.com/en-us/kb/286335.

SQL Insert statement not working C#

Using Access database like this :
OleDbConnection conn = new OleDbConnection(#"Provider=Microsoft.ACE.OLEDB.12.0; Data Source=" + Request.PhysicalApplicationPath + "Resources/cars_db.accdb");
conn.Open();
OleDbCommand cmd = conn.CreateCommand();
cmd.CommandText = "INSERT INTO Users (Username, Password, Email, Address, Question, Answer) VALUES ('" + txtUsernameRP.Text + "','" + txtPasswordRP.Text + "','" + txtEmailRP.Text + "','" + txtAddressRP.Text + "','" + txtQuestionRP.Text + "','" + txtAnswerRP.Text + "')";
int i = cmd.ExecuteNonQuery(); -- **Breaks here and says syntax error**
I have tried:
Taking out the int i bit.
Putting the # symbol in front of the statement.
Checked and made sure that I am using the Access code.
Tried closing the connection before creating in case it was something there.
Substituted the data for fixed values, which I then ran in a query in Access which worked.
Put the access query mentioned above into the code block (cmd.CommandText = "INSERT INTO Users (Username, Password, Email, Address, Question, Answer) VALUES ('asdasd','Asd!23asd','asdasd','asdasd','asdasd','asdasd')"; and tried running it and again same syntax error.
Please someone help me...
Password is reserved keyword
cmd.CommandText = "INSERT INTO Users (Username, Password, Email, Address...
try this
cmd.CommandText = "INSERT INTO Users (Username, [Password], Email, Address...
Can You try this?
"INSERT INTO Users (Username, Password, Email, Address, Question, Answer)
VALUES(
'" + txtUsernameRP.Text + "',
'" + txtPasswordRP.Text + "',
'" + txtEmailRP.Text + "',
'" + txtAddressRP.Text + "',
'" + txtQuestionRP.Text + "',
'" + txtAnswerRP.Text + "');";
I guess your problem is on that int i, try removing it

Apostrophe causes a query issue

When I execute a query for the population of a table I get an error on only two occurrence. In particular, when the name field has some value like this:
K'Ogladbach
Now the apostrophe causes an issue, because the query interprets this command like a new value and this is wrong.
This is my structure for the query in SQL:
string sql = #"insert into Team (name, code, shortName, squadMarketValue,
crestUrl, link_self, link_fixtures, link_players, caption)
values ('" + item.name + "', '" + item.code + "', '" +
item.shortName + "', '" + item.squadMarketValue + "', '" +
item.crestUrl + "', '" + item._links.self.href + "', '" +
item._links.fixtures.href + "', '" + item._links.players.href + "', '" +
campionato + "')";
how you can see each new value is rapresented by ' value ',
so if in the value there's a " ' " it's a problem because the query failed the table population. Hopefully, there is a solution.
Use SqlParamerterized queries rather than raw SQL. This will help prevent SQL Injection and also provide a robust solution.
SqlCommand command = new SqlCommand("INSERT INTO Team (name) VALUES (#name)", con);
command.Parameters.Add("#name", SqlDbType.NVarChar).Value = item.name;
// Add the rest of the parameters here
command.ExecuteNonQuery(); // Execute the command
SqlParamerterized queries is the best approach
You can also replace a ' with a '' in the data
That is not a double quote - it is two single quotes
E.G. K'Ogladbach to K''Ogladbach

Error with SQL syntax (in Windows form , C#)

I'm trying to insert some data into my table and that's how I try to do it
INSERT INTO OrdersDetail
Values (" + OrderId.Text + ", (SELECT IdProduct FROM Products WHERE ProductName = '" + listBox1.Text + "'), '" + TypeOfProductComboBox.Text + "', '" + OrderQuantity.TextAlign + "', '" + TotalCost.Text + "'");
and I'm geting error I think my syntax is wrong, I'm use query in query to get the product id.
The columns are :
OrderId (int)
ProductId(int)
ProductName(Nvarchar)
OrderQuantity(Nvarchar)
TotalCost(NvarChar)
Thanks
You set your inside SELECT under '. Should be:
var query = "INSERT INTO OrdersDetail Values (" + OrderId.Text + ", (SELECT IdProduct FROM Products WHERE ProductName = '"+ listBox1.Text + "'), '" + TypeOfProductComboBox.Text + "', '" + OrderQuantity.TextAlign + "', '" + TotalCost.Text + "')");
If for example TotalCost.Text is a numeric data type in SQL, use
"..." + OrderQuantity.TextAlign + "', " + Convert.ToDouble(TotalCost.Text) + ")";
As p.s.w.g stated: This is open for SQL injection. Replace it with a parameterized version!
I think the problem is with the first Line and your inside Select.
This should work
INSERT INTO OrdersDetail
Values ('" + OrderId.Text + "',(SELECT IdProduct FROM Products WHERE ProductName ='"+ listBox1.Text + "')," + TypeOfProductComboBox.Text + "','" + OrderQuantity.TextAlign + "','" + TotalCost.Text + "'");
The problem is that you are missing the last bracket, the query should finish with "')" instead of "'" . The initial code started with opening bracket and that is why you didn't get compile errors.
But you should not create such sql queries, use Parameters to avoid SQL injection attacks. You code is vulnerable to them.

insert statement wont work

Hey guys I get no errors from my code but nothing seems to happen when i try my insert statement below?
Not sure if its how I wrapped my textbox or if its my FriendID query string?
protected void Button1_Click(object sender, EventArgs e)
{
string friendid = Request.QueryString["FriendID"];
string theUserId = Session["UserID"].ToString();
using (OdbcConnection cn = new OdbcConnection("Driver={MySQL ODBC 3.51 Driver}; Server=localhost; Database=***; User=***; Password=***;"))
{
cn.Open();
using (OdbcCommand cmd = new OdbcCommand("INSERT INTO WallPosting (UserID, Wallpostings, FriendUserID) VALUES (" + friendid + ", '" + TextBox1.Text + "', " + theUserId + ")", cn))
{
cmd.ExecuteNonQuery();
}
}
PopulateWallPosts(friendid);
}
}
You switched your variables, according to the field names it should be:
using (OdbcCommand cmd = new OdbcCommand("INSERT INTO WallPosting (UserID, Wallpostings, FriendUserID) VALUES (" + theUserId + ", '" + TextBox1.Text + "', " + friendid + ")", cn))
New record has been added, but for the wrong user so you didn't find it later when reloading the posts.
As you've been told already deal with the SQL Injection risk by using Parameters instead of directly adding the values to the SQL string.
"INSERT INTO WallPosting (UserID, Wallpostings, FriendUserID) VALUES (" + friendid + ", '" + TextBox1.Text + "', " + theUserId + ")"
becomes
"INSERT INTO WallPosting (UserID, Wallpostings, FriendUserID) VALUES ('" + friendid + "', '" + TextBox1.Text + "', '" + theUserId + "')"
Have to qualify the strings using single quotes. otherwise they are treated as variables by the parser.

Categories

Resources