简体   繁体   中英

How can I replace a variable with the defined value of this variable in MySQL?

Assign a string to a defined variable isWeekdays ,

set @isWeekdays='calendar.monday=1 AND calendar.tuesday=1 AND calendar.wednesday=1 AND calendar.thursday=1 AND calendar.friday=1';

I expect that the variable isWeekdays can be replaced with the string while executing a query, for instance,

SELECT * FROM calendar WHERE @isWeekdays;

-- expect to    
SELECT * FROM calendar WHERE calendar.monday=1 AND calendar.tuesday=1 AND calendar.wednesday=1 AND calendar.thursday=1 AND calendar.friday=1;

However, it does not take effect.

@isWeekdays will evaluate as numeric in query, you must use a statement and it will work as dynamic query:

-- setting the @isWeekdays variable
set @isWeekdays='calendar.monday=1 AND calendar.tuesday=1 
     AND calendar.wednesday=1 AND calendar.thursday=1 
      AND calendar.friday=1';


-- using the @isWeekdays variable in dynamic query
set @sql = concat('SELECT * FROM calendar WHERE ',@isWeekdays);
prepare stmt1 FROM @sql; 
execute stmt1; 
-- you muyst close the prepared statement
deallocate prepare stmt1; 

You can change @isWeekdays in the same session and open the statement again.

That's it.

With the help of @Notorious Pet0 , compared with dynamic queries , using script language seems better. The key source codes (using format strings in python ) is as follows.

#!/usr/bin/env python
import MySQLdb
import codecs  #for charset utf-8

## connect to MySQL
db = MySQLdb.connect(host="localhost",
        user="root",
        passwd="Jelline", # password
        db="gtfs")  #name of the data base

## create a Cursor object to execute sql queries
cur = db.cursor()

## execute queries
isWeekdays = 'calendar.monday=1 AND calendar.tuesday=1 AND calendar.wednesday=1 AND calendar.thursday=1 AND calendar.friday=1'
sql = 'SELECT * FROM calendar WHERE {isWeekdays}'.format(isWeekdays=isWeekdays)

cur.execute(sql)

## write to a file
with open('test.txt', 'w') as fp : #fp is a file object
    for row in cur.fetchall() :
        s = '\t'.join(str(item) for item in row)
        fp.write(s + '\n')

## clean up
fp.close()
cur.close()
db.close()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM