Classic ASP / Parameterized Full Text Query - asp-classic

When writing parameterized queries in Classic ASP, I have been using the following syntax:
Set cmdConn = Server.CreateObject("ADODB.Command")
Set cmdConn.ActiveConnection = Conn
cmdConn.Prepared = True
SQL = " INSERT INTO myTable (column1, column2, column3) VALUES (?, ?, ?); "
Set newParameter = cmdConn.CreateParameter("#column1", ad_Integer, ad_ParamInput, Len(input1), input1)
cmdConn.Parameters.Append newParameter
Set newParameter = cmdConn.CreateParameter("#column2", ad_Integer, ad_ParamInput, Len(input2), input2)
cmdConn.Parameters.Append newParameter
Set newParameter = cmdConn.CreateParameter("#column3", ad_Integer, ad_ParamInput, Len(input3), input3)
cmdConn.Parameters.Append newParameter
cmdConn.CommandText = SQL
cmdConn.Execute
And I'm of the understanding (self-taught), that where I use #column1 when appending a new parameter, this allocates the parameter to that particular column. I could be wrong tho'. So this has totally confused me when trying to write a full-text query.
This is my original full-text query:
SQL = "SELECT * FROM myTable WHERE MATCH (column1, column2, column3) AGAINST ('"&input&"' IN BOOLEAN MODE)"
Could somebody show me what syntax to use for this query?
I would imagine the SQL would look like this:
SQL = "SELECT * FROM myTable WHERE MATCH (column1, column2, column3) AGAINST (? IN BOOLEAN MODE)"
But not sure what to put for the newParameter string. Any help and explanations gratefully received...

"#columnN" is the name of that parameter, and isn't related to the column columnN. This field is optional, so it could be unspecified for all of your parameters if you are never going to use the name when referring to it.
It can be used for retrieving the value of output and input/output parameters from the Command object, instead of referring to the parameter by the order in which it was appended to the Parameters collection. I believe that some DBMSs will also support using named parameters in the query string instead of ? (easier to read, presumably).
To answer your specific question,
Set newParameter = cmdConn.CreateParameter(, adInteger, adParamInput, Len(input), input)
cmdConn.Parameters.Append newParameter

Related

The multi-part identifier could not be bound error won't fix

The Variable fileName contains the name of two columns to fetch value of it, which is in the type of "email,address"
The output of the fileName variable is sam#gmail.com102streetN, which is what I need
but when I try to insert that value into another column table then it throws me an error
The multi-part identifier "sam#gmail.com102streetN" could not be bound.
I don't know how to fix it
for each a in idParase
strSQL = "Select Award, Year, ("&fileName&") as dynamicColumns FROM dbo.Awards_TABLE Where awardID = "&a&""
cmdCRProc.CommandText = strSQL
Set rsCR = cmdCRProc.Execute
nameParase = rsCR("dynamicColumns")
sql2 = "Insert Into dbo.Queue (Award,Year,awardID,FileName) Values ("&rsCR(0)&", "&rsCR(1)&", "&a&", "&nameParase&") "
cmdCRProc.CommandText = sql2
Set rsCR = cmdCRProc.Execute
next
I think this isn't going wrong in the INSERT, but in the SELECT.
If I write out your SELECT it would be something this I think (I don't know the value of "a", but let's say it's 2):
Select Award, Year, (sam#gmail.com102streetN) as dynamicColumns FROM dbo.Awards_TABLE Where awardID = 2
I very much doubt you have a column named 'sam#gmail.com102streetN', right?
I don't know what your goal is, but it seems like you're building a query with a dynamic column name that doesn't exist.
What you can do is Response.Write() your SQL statements and see what the result is. Then maybe run them in your database management tool to check what's going on:
Response.write(strSQL)
And
Response.write(sql2)

Android SQLITE Insert into table with values coming from a subquery

In my db-driven app I need to perform insert into queries in which the value for one or more field comes from a subquery.
The insert into statement may look like the following example:
INSERT INTO MyTable (field_1, field_2)
VALUES('value for field 1', (SELECT field_x FROM AnotherTable WHERE ...))
At present I am doing it manually building the query:
String MyQuery = "INSERT INTO mytable (field_1, field_2)
VALUES('value for field 1', (SELECT field_x FROM AnotherTable WHERE ...))"; // Of course my query is far more complex and is built in several steps but the concept is safe, I end up with a SQL String
SQLiteDatabase= db = getWritableDatabase();
db.execSQL(MyQuery); // And it works flawlessy as it was a Swiss Clock
What i would like to do instead is:
SQLiteDatabase db = getWritableDatabase();
ContentValues values = new ContentValues();
values.put("field_1", "value for field 1");
values.put("field_2", ThisIsAQuery("(SELECT field_x FROM AnotherTable WHERE ...)"));
db.insert("MyTable", null, values);
db.close();
Where the fake method ThisIsAQuery(...) is the missing part, something that should tell the query builder that "SELECT.." is not a value but a query that should be embedded in the insert statement.
Is there a way to achieve this?
The whole point of the ContentValues container is to be able to safely use strings without interpreting them as SQL commands.
It is not possible to use subqueries with insert(). The only way to get a value from another table is by executing a separate query; in this case, ThisIsAQuery() would be stringForQuery() or longForQuery().

"Row value misused" error in SQLite database

I'm getting an error from an sqlite3 query for which I can't find any reference material. Googling the string takes me deep in the SQLite code itself, and that's so opaque I can't make heads or tails of it.
The table schema:
CREATE TABLE quote (
seqnum INTEGER,
session STRING,
timestamp_sip INTEGER,
timestamp_1 INTEGER,
market_center STRING,
symbol STRING,
bid_price INTEGER,
bid_lots INTEGER,
offer_price INTEGER,
offer_lots INTEGER,
flags INTEGER,
PRIMARY KEY (symbol, seqnum) );
The query:
select (seqnum, session, timestamp_sip, timestamp_1, market_center, symbol)
from quote
where symbol = 'QQQ';
The error:
Error: row value misused
I have no idea how to proceed here. There is plenty of data in the table that would match the query:
sqlite> select count(*) from quote where symbol = 'QQQ';
2675931
Can anyone offer any guidance here? Sqlite version is 3.16.2.
Nevermind. Those parentheses around the select columns (left over from a copy/paste) are the problem. Poor error message, maybe. But my fault.
I had a similar when working with a Rails 5.2 Application.
For my case I was trying to write a search query for a model in application:
def self.search(params)
applications = all.order('created_at DESC') # for not existing params args
applications = applications.where("cast(id as text) like ?, email like ?, first_name like ?, last_name like ?, appref like ?", "#{params[:search]}", "%#{params[:search]}%", "#{params[:search]}", "#{params[:search]}", "#{params[:search]}",) if params[:search]
applications
end
The issue was that I was using a comma (,) to separate the search parameters, I simply corrected by using an OR instead:
def self.search(params)
applications = all.order('created_at DESC') # for not existing params args
applications = applications.where("cast(id as text) like ? OR email like ? OR first_name like ? OR last_name like ? OR appref like ?", "#{params[:search]}", "%#{params[:search]}%", "#{params[:search]}", "#{params[:search]}", "#{params[:search]}",) if params[:search]
applications
end
I deleted brackets from query and it work for me: from SELECT (column1, column2, ...) FROM table to SELECT column1, column2, ... FROM table
JUST
select seqnum, session, timestamp_sip, timestamp_1, market_center, symbol
from quote
where symbol = 'QQQ';
then it works.
Yeah, this bug is happing in my code, and I found this questions, but none of the answers helped me.
I fixed this problem with remove the same column in my SELECT command.
(It's stupid, because I can't select the column if the column is already in the condition subcommand.)
This is the problem SQL command (DO NOT USE THIS):
SELECT (`id`, `username`) FROM `users` WHERE `id` = 'someone_s id'
This is the fixed SQL command (PLEASE USE THIS):
SELECT (`username`) FROM `users` WHERE `id` = 'someone_s id'
The same error occurs when putting the elements of a GROUP BY clause inside brackets, as in
SELECT 1 as a, 2 as b FROM (SELECT 1) GROUP BY (a, b);
The correct syntax is, of course
SELECT 1 as a, 2 as b FROM (SELECT 1) GROUP BY a, b;

sqlite with boolean values?

i am getting some text and boolean values from server i need to save them in database.
this is my table . I defined boolean values as INTEGER couse in sqlite there is no boolean.
db.execSQL("CREATE TABLE outcomesStore(id INTEGER PRIMARY KEY AUTOINCREMENT , allowgo INTEGER,cod TEXT,youdidComments INTEGER, youwent INTEGER,ByDate INTEGER ," +
"OnCompletion INTEGER,yourtext TEXT , yourGroup TEXT, yourConsultation INTEGER )");
and i am getitng these values from server.
Store[] Storedata = Configuration.getStore();
booleanvalues[0] = Store[0].isallowgo ();
and inserting like this
helperdatabase = new DatabaseHelperInurseBusiness(this);
db = helperdatabase.getWritableDatabase();
ContentValues insertOutcomes = new ContentValues();
insertOutcomes.put(helperdatabase.ALLOW_GO,booleanvalues[0]);
db.insert("outcomesStore", helperdatabase.ALLOW_GO,insertOutcomes);
Its not working even not giving any error.
Actually, SQLite does support BOOLEAN type, but may be not exactly in the way you expect.
You can create column of BOOLEAN type using standard CREATE TABLE, and then populate it:
CREATE TABLE mytable (name VARCHAR(10), flag BOOLEAN);
INSERT INTO mytable (name, flag) VALUES ('Alice', 0);
INSERT INTO mytable (name, flag) VALUES ('Bob', 1);
Then you can get your data back, and use standard BOOLEAN logic while doing so:
SELECT * FROM mytable WHERE flag
or using different BOOLEAN expressions:
SELECT * FROM mytable WHERE NOT flag
and so on. (Obligatory SQLFiddle)
In other words, it all works great, the only catch is that you must use 0 instead of FALSE and 1 instead of TRUE (this includes trying to set values from client software). Note that this is somewhat similar to other SQL engines (For example, PostgreSQL supports using '0'/'1', 'f'/'t' and false/true for setting FALSE/TRUE values by client software).
Also, if you were to use this BOOLEAN field in numeric context (like adding or multiplying) it will behave as number 0 or 1, while in other SQL engines adding BOOLEAN and INTEGER may cause an exception because of incompatible types.
i got the solution.
Thanks Yaqub Ahamad.
insertOutcomes.put(DatabaseHelperInurseBusiness.ALLOW_GO,storedata.isAllowGo()== true ? 1:0);

Having problems with sqlDataReader

I am using a sqlDataReader to get data and set it to session variables. The problem is it doesn't want to work with expressions. I can reference any other column in the table, but not the expressions. The SQL does work. The code is below. Thanks in advance, Anthony
Using myConnectionCheck As New SqlConnection(myConnectionString)
Dim myCommandCheck As New SqlCommand()
myCommandCheck.Connection = myConnectionCheck
myCommandCheck.CommandText = "SELECT Projects.Pro_Ver, Projects.Pro_Name, Projects.TL_Num, Projects.LP_Num, Projects.Dev_Num, Projects.Val_Num, Projects.Completed, Flow.Initiate_Date, Flow.Requirements, Flow.Req_Date, Flow.Dev_Review, Flow.Dev_Review_Date, Flow.Interface, Flow.Interface_Date, Flow.Approval, Flow.Approval_Date, Flow.Test_Plan, Flow.Test_Plan_Date, Flow.Dev_Start, Flow.Dev_Start_Date, Flow.Val_Start, Flow.Val_Start_Date, Flow.Val_Complete, Flow.Val_Complete_Date, Flow.Stage_Production, Flow.Stage_Production_Date, Flow.MKS, Flow.MKS_Date, Flow.DIET, Flow.DIET_Date, Flow.Closed, Flow.Closed_Date, Flow.Dev_End, Flow.Dev_End_Date, Users_1.Email AS Expr1, Users_2.Email AS Expr2, Users_3.Email AS Expr3, Users_4.Email AS Expr4, Users_4.FNAME, Users_3.FNAME AS Expr5, Users_2.FNAME AS Expr6, Users_1.FNAME AS Expr7 FROM Projects INNER JOIN Users AS Users_1 ON Projects.TL_Num = Users_1.PIN INNER JOIN Users AS Users_2 ON Projects.LP_Num = Users_2.PIN INNER JOIN Users AS Users_3 ON Projects.Dev_Num = Users_3.PIN INNER JOIN Users AS Users_4 ON Projects.Val_Num = Users_4.PIN INNER JOIN Flow ON Projects.id = Flow.Flow_Pro_Num WHERE id = "
myCommandCheck.CommandText += QSid
myConnectionCheck.Open()
myCommandCheck.ExecuteNonQuery()
Dim count As Int16 = myCommandCheck.ExecuteScalar
If count = 1 Then
Dim myDataReader As SqlDataReader
myDataReader = myCommandCheck.ExecuteReader()
While myDataReader.Read()
Session("TL_email") = myDataReader("Expr1").ToString()
Session("PE_email") = myDataReader("Expr2").ToString()
Session("DEV_email") = myDataReader("Expr3").ToString()
Session("VAL_email") = myDataReader("Expr4").ToString()
Session("Project_Name") = myDataReader("Pro_Name").ToString()
End While
myDataReader.Close()
End If
End Using
This may be because column names need to be unique for the SqlDataReader to be able to index them using a string name for the column.
A couple of things:
1) You are executing the query 3 times. You can lose the ExecuteNonQuery and ExecuteScalar calls, and replace the while loop with "if myDataReader.Read() / end if" to get the data values for the first resulting record. If no records are found, no session variables are set, just as in your current code.
2) It looks more like the problem lies in your session management (ie getting values from Session) rather than your sql query, which looks OK to me.
Check:
that you have sessionState enabled in your web.config file,
that you don't reset the Session values anywhere, and
that you ask for the same Session field name when you are trying to send the email. (e.g. are you setting Session("DEV_Email") but asking for Session("DEV Email") (space instead of underscore) ?
Sorry everyone. The code works just fine. The sqlDataReader WILL accept expressions as column names.
The reason I was getting an error saying the value of the from and to parameters cannot be null. There was no data in that column for any of the records in my table.

Resources