Sqlite insert gives syntax error - sqlite

I am working on flex actionscript project. In which i am going to save/insert records in sqlite database, which i got in response.
But, form that records some records are not inserted into table. When i catch the error it gives sql error.
near '/': syntax error
In response i have got whole html markup.
I have written/execute query inside for loop like:
var insert:SQLStatement = new SQLStatement();
insert.sqlConnection = sqlConnectionSync;
insert.text = 'INSERT OR IGNORE INTO TableName (MessageID, AccountID, Body) VALUES ("' + listArray[i].MessageID + '","' + listArray[i].AccountID + '","' + listArray[i].Body + '")';
insert.execute();
I have also tried changing " in place of ' and vice versa.
But it gives other error of '
Error #3115: SQL Error.
near 'll': syntax error
And
near '_blank': syntax error
Any help would greatly appreciated.

To avoid such problem, you can use SQLStatement.parameters property like this, for example :
var insert:SQLStatement = new SQLStatement();
insert.text = 'INSERT OR IGNORE INTO TableName (MessageID, AccountID, Body) VALUES (:param1, :param2, :param3)';
insert.parameters[':param1'] = listArray[i].MessageID;
insert.parameters[':param2'] = listArray[i].AccountID;
insert.parameters[':param3'] = listArray[i].Body;
insert.execute();
Hope that can help.

Posting the full query as text would help but most likely you have " or ' characters in your data (like ...="_blank" or "You'll"). You'd need to escape your variable values before inserting them into the database. I have switched " and ' from your example:
insert.text = "INSERT OR IGNORE INTO TableName (MessageID, AccountID, Body) VALUES ('" + escapeChars(listArray[i].MessageID) + "','" + escapeChars(listArray[i].AccountID) + "','" + escapeChars(listArray[i].Body) + "')";
private function escapeChars(myString:String):String
{
// Since we are using "'" we'd need to escape all other "'" characters
return myString.replace(/'/gi, "\'");
}

Related

What is wrong with the Search Form codes?

I have a Search Form which have a sub form in it.
I keep getting Run-time error '3075': Syntax error(missing operator) in query expression '[MC_No] like '' [Customer] like '' [Date_Recorded] = #23/11/2016# AND [Product] like '*".
Can anybody identify my error? I have checked every single line. Maybe I missed out on something.
These are my codes
Private Sub Search_Click()
Dim strDatePicker As String
Dim cboMC As String
Dim strProduct As String
Dim cboCustomer As String
Dim sql As String
sql = "select * FROM 3_OEE WHERE "
If IsDate(Me.DatePicker) Then
strDatePicker = " [Date_Recorded] = #" & DateValue(Me.DatePicker) & "#"
Else
strDatePicker = " [Date_Recorded] like '*'"
End If
If IsNull(Me.MC_No) Then
cboMC = " [MC_No] like '*'"
Else
cboMC = " [MC_No] like '" & Me.MC_No & "'"
If IsNull(Me.Customer) Then
cboCustomer = " [Customer] like '*'"
Else
cboCustomer = " [Customer] = '" & Me.Customer & "'"
End If
Me.subfrmOEE.Form.RecordSource = sql (*Error highlights this code*)
Me.subfrmOEE.Form.Requery
On the line with the error, your variable sql is the same as it was when you first declared it, i.e.: "select * FROM 3_OEE WHERE ".
This is not a valid query. You need to either remove WHERE from the end of that query or append to the sql variable the rest of the query statement (in other words, add the WHERE conditions to the end of the query).

How to make value of a column name appear with single apostrophe in sql statement of sql helper inside asp. net

SQLHelper sqhlpr = new SQLHelper();
sqhlpr.SqlText = "Select StudentName from tblStudentInfo where class=" + NurseryButton.Text;
DataTable dt = sqhlpr.getDataTable(false);
This is my code.Now the result of sqhlpr.sqlText is
select StudentName from tblStudentInfo where class= **Nursery**
(i.e.NurseryButton.Text=Nursery) but the result that i want is select StudentName from tblStudentInfo where class= 'Nursery'.How can this be done??? This looks simple but I can't just figure it out...
"Select StudentName from tblStudentInfo where class='" + NurseryButton.Text + "'";
But you definitively should not use it that way! (SQL Injection)
Here is a good answer: Sql inline query with parameters. Parameter is not read when the query is executed
Your query is a string. You do:
result = "somestring" + someVariable;
Now you want to enclose someVariable in sinlge quotes, which is done like this:
result = "somestring" + "'" + someVariable + "'";
Or shorter:
result = "somestring'" + someVariable + "'";
However is is worth noting that manually building queries is quite "not done". You should look at tools like parameterized queries or even O/R mappers like Entity Framework.
The following code will do what you want:
SQLHelper sqhlpr = new SQLHelper();
sqhlpr.SqlText = "Select StudentName from tblStudentInfo where class = '" + NurseryButton.Text + "'";
DataTable dt = sqhlpr.getDataTable(false);
You need to think about two more things though:
What happens if someone puts an apostrophe in the NurseryButton.Text somehow
Will SQLHelper protect you from this sort of thing, or do you need to do it yourself
You should consider parametrized querying or stored procedures in some way to make sure that your input to the database is done safely.

Asp.net add to database

Is it possible to add from a single textbox to different tables in a database.
I have a addclub webform and i would like to add clubname to a number of different tables.
The following is my current code that i have.
cmd = new SqlCommand("insert into youthclublist(youthclubname, description, address1, address2, county, postcode, email, phone) values ('" + youthclubname.Text + "', '" + description.Text + "','" + address1.Text + "','" + address2.Text + "', '" + county.Text + "', '" + postcode.Text + "', '" + email.Text + "', '" + phone.Text + "')", connection);
It is possible yes but consider my point below:
Think about normal form, it should be possible to design the database so that you only need to alter it on one place. If you have to change the name in several places it is likely not following normal form and the database could be redesigned.
The way you are doing the update is not advisable, have a look into SQLInjection attacks as the above code is vulnerable to this. Using parameters in the SQLCommand rather than creating a big string is a better way to do this from a security and performance point.
Hope I have not been too negative
Andy
You can do it if you use a transaction (and you should use parameters to get around some SQL injection attack problems) like so (this means that all the inserts are done in a single block on the database which is safer than doing them one after the other):
using (var cmd = new SqlCommand("BEGIN TRANSACTION;"
+ "INSERT INTO youthclublist(youthclubname) VALUES (#youthclubname);"
// Add all your INSERT statements here for the other tables in a similar way to above (I simplified it to show just one column, but you get the idea)
+ "COMMIT;", conn))
{
// Add your parameters - one for each of your text boxes
cmd.Parameters.Add("#youthclubname", SqlDbType.NVarChar).Value = youthclubname.Text;
// execute the transaction
cmd.ExecuteNonQuery();
}

Insert the date into table

I am trying to get From date and To date in two text boxes using the calender control and then trying to insert this value in a table. How can I proceed with this??
Please help..
string comstr = "insert into ATM_DETAILS_TB values(" + txtpin.Text + ",'" + Convert.ToDateTime(txtvldfrm.Text) + "','" + Convert.ToDateTime(txtvldto.Text) + "'," + Convert.ToInt32(ddlaccno.SelectedValue) + ",'" + Session["strUid"].ToString() + "')";
while using this code it shows error like "String was not recognized as a valid DateTime"
what should I do??
Use Validation controls to validate that the values in textbox values are valid dates.
Your code us contencating strings directly from user input. This opens you up to all sorts of nasty attacks, the primary being SQL Injection. Use parameterized queries instead.
Always use DateTime.TryParse or TryParseExact method to parse the date.
DateTime vldDate;
bool isValid=false;
if(DateTime.TryParse(txtvldfrm.Text,out vldDate))
{
isValid=true;
}
....
if(isValid)
{
command.Parametter.Add("#vldto",SqlDbType.DateTime).Value=vldDate;
command.Parametter.Add("#strUid",SqlDbType.VarChar,30).Value=Session["strUid"];
.....
}
You Use from parameterized queries like this:
string comstr = "insert into ATM_DETAILS_TB values(#pin,#vldfrm,#vldto,#ddlaccno,#strUid)";
YourCommand.Parametter.AddWithValue("#vldto",Convert.ToDateTime(txtvldto.Text));
YourCommand.Parametter.AddWithValue("#strUid",Session["strUid"].ToString());
....Define the Other Paraametter
Edit----
check this question String was not rec...

Issue with ODBC.Net connection to MySQL DB

I'm thinking the problem here is with my SQL Syntax, but I'm not sure and need a fresh pair of eyes to check it out. This is the code I'm using to connect to and then insert into the DB:
OdbcConnection datConn = CreateDataConn();
datConn.Open();
OdbcCommand comm = new OdbcCommand();
comm.CommandText = "INSERT INTO userdata (key, secretkey, uid) VALUES ('" + token + "', '" + secret + "', '" + twitterid + "');";
comm.Connection = datConn;
comm.ExecuteNonQuery();
datConn.Close();
And here is the CreatDataConn() method:
private OdbcConnection CreateDataConn()
{
OdbcConnection dbConn = new OdbcConnection();
dbConn.ConnectionString = "Dsn=MySQL;database=twittertest;option=0;port=0;server=localhost;uid=root;pass=Red!4jedi";
return dbConn;
}
I created a DSN to the database, which is hosted on my machine.
When I run the application I get this error:
ERROR [42000] [MySQL][ODBC 3.51 Driver][mysqld-5.1.51-community]You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'key, secretkey, uid) VALUES ('127090765-i3aZl71LPSVUCPZs9kHSYeBli0vWpbq0BaM1roYC' at line 1
But for the life of me I can't figure out what's wrong with my syntax...It's prolly something simple, but again, I need a pair of fresh eyes to look at this.
key is a probably a reserved word. in MySQL, you can get around this by adding backticks (`) around a column name (so '`key`'instead of 'key'), but you should try not to have reserved words as entity names.

Resources