I am using only two columns 1.name 2.field. i need to retrieve name where field is =? how to specify.i dont want this--> (self.topic_space,)) i need the second column.so where to put the comma
Here is my code :
cur.execute("SELECT name FROM developers_info WHERE field=?",(,self.topic_space))
File "administrator.py", line 19
cur.execute("SELECT * FROM developers_info WHERE field=?",(,self.topic_space))
^
Here is my error :
SyntaxError: invalid syntax
It looks like you may have a rogue comma. Try this
cur.execute("SELECT name FROM developers_info WHERE field=?",(self.topic_space))
Related
I'm trying to retrieve some data from a postgresql database using psycogp2, and either exclude a variable number of rows or exclude none.
The code I have so far is:
def db_query(variables):
cursor.execute('SELECT * '
'FROM database.table '
'WHERE id NOT IN (%s)', (variables,))
This does partially work. E.g. If I call:
db_query('593')
It works. The same for any other single value. However, I cannot seem to get it to work when I enter more than one variable, eg:
db_query('593, 595')
I get the error:
psycopg2.DataError: invalid input syntax for integer: "593, 595"
I'm not sure how to enter the query correctly or amend the SQL query. Any help appreciated.
Thanks
Pass a tuple as it is adapted to a record:
query = """
select *
from database.table
where id not in %s
"""
var1 = 593
argument = (var1,)
print(cursor.mogrify(query, (argument,)).decode('utf8'))
#cursor.execute(query, (argument,))
Output:
select *
from database.table
where id not in (593)
Background
Framework: Codeignighter/PyroCMS
I have a DB that stores a list of products, I have a duplicate function in my application that first looks for the common product name so it can add a 'suffix' value to the duplicated product.
Code in my Products model class
$product = $this->get($id);
$count = $this->db->like('name', $product->name)->get('products')->num_rows();
$new_product->name = $product->name . ' - ' . $count;
On the second line the application fails only when the $product->name contains quotes.
I was with the understanding that Codeignighter escaped all strings so I dont know why I get this error.
So I tried to use MySQL escape string function but that didn't help either.
The Error Message
A Database Error Occurred
Error Number: 1064
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 's Book%'' at line 3
SELECT * FROM `products` WHERE `name` LIKE '%Harry\\'s Book%'
var_dump
Below is the output of doing a var_dump on product->name before and after the line in question;
string 'Harry's Book' (length=12)
A Database Error Occurred
Error Number: 1064
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 's Book%'' at line 3
SELECT * FROM `products` WHERE `name` LIKE '%Harry\\'s Book%'
Let's do some testing about this.
Here is what you are doing
$count = $this->db->like('name', $product->name)->get('products')->num_rows();
And i suspect $product->name contains this.
Harry's Book
As we know this is coming from the database table as you are using.
Where you are using the upper query mentioned it is wrapping it with
single quotes and producing this result.
SELECT * FROM `products` WHERE `name` LIKE '%Harry\\'s Book%'
As you see it is escaping apostrophy to tell it is not end of string
Therefore escaping it with two slashes.One for apostrophy and one for being in single quote.
What you have to do is
Before assigning the parameter to query wrap it with double quotes.
$product_name = "$product->name";
And now pass it to query.
$count = $this->db->like('name', $product_name)->get('products')->num_rows();
The output will be this
SELECT * FROM `products` WHERE `name` LIKE '%Harry\'s Book%'
You see the differece here. It contains single slash now and the record will
be found.
Other answers didn't work for me, this does though:
$count = $this->db->query("SELECT * FROM `default_firesale_products` WHERE `title` LIKE '".addslashes($product['title'])."'")->num_rows();
Whenever CI Active Record mangles your queries you can always just put a raw query in instead and have full control.
Try this, using stripslashes() around $product->name:
$count = $this->db->like('name', stripslashes($product->name))->get('products')->num_rows();
CI automatically escapes characters with active records but I bet that it's already escaped if you entered it previously via active record in CI. So now it is doing a double escape.
Update: You may also want to try adding the following before you query:
$this->db->_protect_identifiers = FALSE;
Last try: try querying this way since it seems like the like active record is causing the error:
$like = $product->name;
$this->db->query("SELECT * FROM `products` WHERE `name` LIKE '%$like%'");
Im trying to make a query that help me get a user by its username. What i want to do is to check if the given username is unique. so what i thought about is to uppercase the username when i do my select request and compare it with an uppercase of the given username. This is what i tried:
SQL("select * from utilisateur where upper(pseudo) = {pseudo}").on(
'pseudo -> pseudo.toUpperCase
).as(Utilisateur.utilisateur.singleOpt)
but it get this error:
[RuntimeException: SqlMappingError(too many rows when expecting a single one)]
I tried this too:
SQL("select * from utilisateur where ucase(pseudo) = {pseudo}").on(
'pseudo -> pseudo.toUpperCase
).as(Utilisateur.utilisateur.singleOpt)
and i got this error:
[PSQLException: ERROR: function ucase(character varying) does not exist Indice : No function matches the given name and argument types. You might need to add explicit type casts. Position : 33]
What should i do ?
PS:Im using PostgreSQL 9.1
First, in Play!, only use singleOpt if you're expecting exactly one row back. Otherwise, it will throw an exception. Since you do want just one row, add a LIMIT 1 to the end of your query.
The PostgreSQL function you want is upper(). Here's an example:
SQL("select * from utilisateur where upper(pseudo) = {pseudo} limit 1").on(
'pseudo -> pseudo.toUpperCase
).as(Utilisateur.utilisateur.singleOpt)
(You can play with it here: http://sqlfiddle.com/#!1/6226c/5)
SQLDF newbie here.
I have a data frame which has about 15,000 rows and 1 column.
The data looks like:
cars
autocar
carsinfo
whatisthat
donnadrive
car
telephone
...
I wanted to use the package sqldf to loop through the column and
pick all values which contain "car" anywhere in their value.
However, the following code generates an error.
> sqldf("SELECT Keyword FROM dat WHERE Keyword="car")
Error: unexpected symbol in "sqldf("SELECT Keyword FROM dat WHERE Keyword="car"
There is no unexpected symbol, so I'm not sure whats wrong.
so first, I want to know all the values which contain 'car'.
then I want to know only those values which contain just 'car' by itself.
Can anyone help.
EDIT:
allright, there was an unexpected symbol, but it only gives me just car and not every
row which contains 'car'.
> sqldf("SELECT Keyword FROM dat WHERE Keyword='car'")
Keyword
1 car
Using = will only return exact matches.
You should probably use the like operator combined with the wildcards % or _. The % wildcard will match multiple characters, while _ matches a single character.
Something like the following will find all instances of car, e.g. "cars", "motorcar", etc:
sqldf("SELECT Keyword FROM dat WHERE Keyword like '%car%'")
And the following will match "car" or "cars":
sqldf("SELECT Keyword FROM dat WHERE Keyword like 'car_'")
This has nothing to do with sqldf; your SQL statement is the problem. You need:
dat <- data.frame(Keyword=c("cars","autocar","carsinfo",
"whatisthat","donnadrive","car","telephone"))
sqldf("SELECT Keyword FROM dat WHERE Keyword like '%car%'")
# Keyword
# 1 cars
# 2 autocar
# 3 carsinfo
# 4 car
You can also use regular expressions to do this sort of filtering. grepl returns a logical vector (TRUE / FALSE) stating whether or not there was a match or not. You can get very sophisticated to match specific items, but a basic query will work in this case:
#Using #Joshua's dat data.frame
subset(dat, grepl("car", Keyword, ignore.case = TRUE))
Keyword
1 cars
2 autocar
3 carsinfo
6 car
Very similar to the solution provided by #Chase. Because we do not use subset we do not need a logical vector and can use both grep or grepl:
df <- data.frame(keyword = c("cars", "autocar", "carsinfo", "whatisthat", "donnadrive", "car", "telephone"))
df[grep("car", df$keyword), , drop = FALSE] # or
df[grepl("car", df$keyword), , drop = FALSE]
keyword
1 cars
2 autocar
3 carsinfo
6 car
I took the idea from Selecting rows where a column has a string like 'hsa..' (partial string match)
I need to reject the rows from an external table which starts (first column of every row) with some special characters (eg. ~ \ etc) in a CSV file.
For that I have used LOAD WHEN clause in the ACCESS PARAMETERS clause. I have been using the following statement in the Access parameters clause:
load when (1:1) != '~'
But it throws an error stating "INVALID CHARACTER"
If I try to use the below statement,
load when (empname != '~empname')
It throws:
ERROR at line 1:
ORA-29913: error in executing ODCIEXTTABLEFETCH callout
ORA-06512: at "SYSTEM.EMP_PROCEDURE", line 101
ORA-06512: at line 1
Line 101 in the procedure is select * from emp;
How do I use LOAD WHEN clause - any examples?
You could use this:
LOAD WHEN (1:1) != 0x'7e'
Reference: http://download.oracle.com/docs/cd/E11882_01/server.112/e16536/et_params.htm#i1009513
Have you tried using the ASCII value of a tilde?
load when (1:1) != CHR(126)