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}
Related
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.
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.
I'm creating my first database with python and I'm using SQLite. I'm following the official tutorial but it's giving me the following error:
UnboundLocalError: local variable 'conn' referenced before assignment
As far as I understand this means it was call too early but I can't understand why.
Below is my code:
import sqlite3
from sqlite3 import Error
def create_connection(db_file):
""" create a database connection to a SQLite database """
try:
conn = sqlite3.connect(db_file)
print(sqlite3.version)
except Error as e:
print(e)
finally:
conn.close()
if __name__ == '__main__':
create_connection("C:\\sqlite\db\pythonsqlite.db")
That tutorial is just horrible.
Here's what's wrong with it:
1) It only works if the path C:\sqlite\db\ already exists on your machine.
2) The notation "C:\\sqlite\db\pythonsqlite.db" (even though correct) should be written as r"C:\sqlite\db\pythonsqlite.db" (notice the leading r that tells Python that this a a raw string) to minimize the chance of a failure due to an escape character (lucky the DB is not called test.db, otherwise C:\\sqlite\db\test.db would point somewhere "funny", since \t will be converted to a TAB).
3) The finally part will always be executed. Now, if your path does not exist, you will see the print unable to open database file - because the DB can not be created. If the DB can not be created, the connection can not be created. If the connection can not be created conn is not defined - but remember we will still execute the finally block.
To sum it up:
If the path does not exists, conn is not defined but conn.close() is still executed, which will result in UnboundLocalError: local variable 'conn' referenced before assignment
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)
I'm using mongoLabs to host my database and I want to connect to it from my app.
I'm also using the Motor module in pyMongo. I'm unsure where to instantiate the connection.
For instance I know that if the database was on same local machine as the app I would do this:
database = motor.MotorClient().open_sync().myDatabase
The mongoLab site says to include the following uri in the driver:
mongodb://<dbuser>:<dbpassword>#ds047057.mongolab.com:47057/myDatabase
But I cannot see how to create the connection to this database.
Thanks
It looks like MotorClient takes the same arguments as MongoClient:
https://github.com/ajdavis/mongo-python-driver/blob/motor/motor/init.py#L782
http://api.mongodb.org/python/current/api/pymongo/mongo_client.html
Given that, you should be able to use the URI like so:
database = motor.MotorClient("mongodb://<dbuser>:<dbpassword>#ds047057.mongolab.com:47057/myDatabase").open_sync().myDatabase
You should to specify connection settings for MotorClient following these manuals:
MotorClient takes the same constructor arguments as MongoClient, as well as, http://emptysquare.net/motor/pymongo/api/motor/motor_client.html#motor.MotorClient,
http://emptysquare.net/motor/pymongo/api/pymongo/mongo_client.html#pymongo.mongo_client.MongoClient
"The host parameter can be a full mongodb URI, in addition to a simple
hostname. It can also be a list of hostnames or URIs. Any port
specified in the host string(s) will override the port parameter. If
multiple mongodb URIs containing database or auth information are
passed, the last database, username, and password present will be
used. For username and passwords reserved characters like ‘:’, ‘/’,
‘+’ and ‘#’ must be escaped following RFC 2396."
db = database = motor.MotorClient('mongodb://<dbuser>:<dbpassword>#ds047057.mongolab.com:47057/myDatabase
').open_sync().myDatabase
Previous answers have got a bit outdated, so the correct way according to the docs and as worked for me:
import motor.motor_asyncio
import asyncio
from asyncio import coroutine
db = motor.motor_asyncio.AsyncIOMotorClient().database_name
https://motor.readthedocs.io/en/stable/tutorial-asyncio.html
https://github.com/mongodb/motor/blob/master/doc/tutorial-asyncio.rst