i'm trying to execute this type of sql command with python but that doesn't work
import pymssql
_conn = pymssql.connect(** SQL parameter)
_cur = _conn.cursor()
_cur.execute("EXEC(SELECT * something)")
i got this error.
Thanks.
The EXECUTE command takes a string, not plain SQL commands:
EXEC('SELECT * something')
But I'm not sure why you're doing this, you could just pass the SELECT statement directly.
Related
I've a script using RobotFramework that makes a lot of database tests. Currently, I am trying to add a new test case that executes a query test from another Python script (called raw_data.py). The raw_data.py is very simple and it only have this code:
query_begin = """SELECT *
FROM my_Table"""
def get_queries_list(query):
result = query.replace('\n','').strip()
return result
query_result = get_queries_list(query_begin)
print(query_result)
So what I want to do is to execute the result (the query) from the previous script using robotframework:
*** Settings ***
Library DatabaseLibrary
Library OperatingSystem
Library raw_data.py
Suite Setup Connect To Database pymysql ${DBName} ${DBUser} ${DBPass} ${DBHost} ${DBPort}
Suite Teardown Disconnect From Database
*** Variables ***
${DBName} myDB
${DBUser} user
${DBPass} pass
${DBHost} hostname
${DBPort} port
${Query} 'SELECT * FROM DEV.personal_tasks'
*** Test Cases ***
Compare the target data with the source data
${output}= Execute SQL String get_queries_list(query)
log to console ${output}
should be equal as strings ${output} 10
But it gives me the following error:
No keyword with name 'Execute SQL String get_queries_list(${Query})' found.
However, the keyword 'Execute SQL String' already exists... what I am doing wrong?
Thanks in advance!!
I think you're missing at least 2 spaces between Execute SQL String and get_queries_list(query) so it evaluates it as a whole, which will then fail and return the error that no such keyword exists.
EDIT:
You also need to save the query into a variable that you later pass to Execute SQL String:
${query}= get_queries_list(query)
Execute SQL String ${query}
I'd like to run multiple statements with one command. Is it possible:
This is the SQL command:
UPDATE toggle SET state='0' WHERE feature_name=‘feature_1;
UPDATE toggle SET state=‘1’ WHERE feature_name=‘feature_2’;
UPDATE toggle SET state=‘1’ WHERE feature_name=‘feature_3’;
For one command I run something like that:
import MySQLdb
myDB = MySQLdb.connect(host=host, port=db_port, user=user, passwd=db_password, db=db)
cHandler = myDB.cursor()
cHandler.execute(query)
But this obviously works only for a single statement
Thanks!
Use parameterized query and executemany.
I am using MySQLdb package in Python to update my database. I have a simple update command as follows :
update_query = "update user_details set `address`='%s' where `id`='%s'"
cursor.execute(update_query, (address, id1))
print(cursor._last_executed)
Here is the command executed :
update user_details set `address`='35, Chikmagalur' where `id`='242069'
The program runs fine without error. However, the database is not getting updated. The same command works when I run as an SQL query on PHPMyAdmin.
Any idea what could be the issue ?
this is a duplicate of ...
sql transactions needs to be committed, either explicitly or implicitly.
either issue a commit command explicitly
cursor._get_db().commit()
setting the connection to autocommit when opening the connection is also an option.
This is a minimum code:
import sqlite3 as sq3
import os
import sys
def main(argv):
q = 'select * from table_name;'
db = 'test.db'
con = sq3.connect(db)
cur = con.cursor()
cur.executescript(q) // cur.execute(q) will work
print cur.fetchone()
if __name__ == '__main__':
sys.exit(main(sys.argv))
My problem is executescript always fails while execute works fine. Is it because executescript is Nonstandard or some libraries I missed?
executescript isn't supposed to return anything, what would it return? The last statement? The first statement? or maybe that one in the middle.
Since it allows you to execute multiple SQL statements there is no way to tell which one you want to have returned.
executescript() is for executing multiple SQL commands, i.e., a script. What is the return value of multiple SQL commands? Hard to say, which is why executescript() returns None. You're not doing anything wrong nor do you have anything missing in your installation.
I want to execute SQL queries from the Python script environment in MySQL Workbench. I looked at the MySQL Workbench documentation for the grt module and found the executeScript method but I can't seem to use it to make queries.
Executing this Python code:
import grt
querystring = "select * from Purchases WHERE PurchaseAmount > 600 and PurchaseAmount < 2500"
executeScript(querystring)
produces the following error message:
Uncaught exception while executing [filepath]runquery.py:
File "[filepath]runquery.py", line 10, in <module>
executeScript(querystring)
NameError: name 'executeScript' is not defined
I don't understand what virtual grt::ListRef executeScript ( const std::string & sql ) means so I can't format my query properly, however, the error message seems to indicate that the executeScript method doesn't exist anyway. Most documentation I look at has examples of correctly-formatted function calls but I can't seem to find any for executeScript.
All I want to do is literally run my string as an SQL query within the MySQL Workbench Python scripting environment.
Thank you!
I am new to Python and SQL so please be patient. :)
To run executeScript function you need to interact with an sqleditor object.
For testing, do the next on MS Windows with the example databases:
Start MySQLWorkbench
connect to local database
select sakila from SCHEMAS
start scripting shell with Tools->scripting shell or (Ctrl+F3)
Add new python script (test.py)
Save script with the content below
run script in scripting shell
Script content:
import grt
result = grt.root.wb.sqlEditors[0].executeScript("select * from actor limit 10;")
for col in result[0].columns:
print col.name
To find out how to reference objects in the script, it is very easy to use the Globals Tree panel's class browser and using right mouse click on the object and choose "Copy Path for Python"
You can run something like the following command if you need to run your script from command line in Windows:
"C:\Program Files\MySQL\MySQL Workbench 6.1 CE\MySQLWorkbench.exe" -query "Local instance MySQL56" -run-python "execfile('c:\Users\Root\AppData\Roaming\MySQL\Workbench\scripts\script.py')" -log-to-stderr -v
The (first) problem seems to be that you use a function called executeScript(), which you haven't defined or taken from anywhere. If it is in the grt module (which I am not familiar with) you have to do it as follows:
from grt import executeScript
querystring = "select * from Purchases WHERE PurchaseAmount > 600 and PurchaseAmount < 2500"
executeScript(querystring)