Deleting a database file in :memory: - python

Background and Question
We are using :memory: to store our database when we are testing and would like to remove this before each test case run so that we will start from the beginning with an empty database for each test case. (If we were storing the database on the disk we would simply remove the file)
Our Setup
We are using Python's unittest module
(Python version: 3.6)
This is what our database creation looks like: db_connection = sqlite3.connect(":memory:")
How can we delete our database from memory?

Use the connection method close(). It will close your connection to the database. If the database is in memory, you should not be able to reconnect to it.
You can test this simply:
import sqlite3
conn = sqlite3.connect(':memory:')
c = conn.cursor()
c.execute('CREATE TABLE test (col1 text, col2 text)')
c.execute("INSERT INTO test VALUES ('good', 'day')")
conn.commit()
conn.close()
We can then check if we can access the database after.
conn = sqlite3.connect(':memory:')
c = conn.cursor()
c.execute("SELECT * FROM test")
print(c.fetchall())
c.execute("SELECT * FROM test")
sqlite3.OperationalError: no such table: test
This shows us that when you close the database in memory, it is destroyed.

Related

MySQL connection with Python through PythonAnywhere

I want to connect to MySql database using Python through PythonAnywhere, without creating a Flask/Django application.
I have seemingly managed to connect through MySQLdb, using the code below, but I do not receive a response when I run the code. Any solutions?
import MySQLdb
db = MySQLdb.connect(
host = "myuser.mysql.pythonanywhere-services.com",
user = "myuser",
passwd = XXX,
db = "myuser$db_name"
)
cursor = db.cursor()
cursor.execute("SELECT * FROM table_name")
for x in cursor:
print(x)
cursor.close()
db.close()
You retrieve all rows in the table, without error.
cursor.execute("SELECT * FROM table_name")
for x in cursor:
print(x)
Yet you see no output. This is normal for a table that contains zero rows.
Consider doing one or more INSERTs, and a COMMIT,
prior to the query.

Python module mysql-connector does not see new changes

I use the mysql.connector module to fetch rows in a python script but when I update a table using the terminal, my script doesen't see any changes.
My code is this:
import mysql.connector
database = mysql.connector.connect(host='localhost', user='root', passwd='password', database='my_db')
cursor = database.cursor()
cursor.execute('SELECT * FROM my_table')
print(cursor.fetchall())
cursor.execute('SELECT * FROM my_table')
print(cursor.fetchall())
The first time it always reads the correct values but at the second time it does not see changes even when I have update my database.
I tried this solutions but it still did not work:
I tried updating the database using the mysql.connector module
I tried installing some older versions
I tried using the root user
When use performs DML like update, delete, etc You have to commit cursor after performing the operation otherwise your operation not save. There are use case of commit cursor some time
due to the electricity issue
atomicity transaction will rollback or commit latter
like
import mysql.connector
database = mysql.connector.connect(host='localhost', user='root', passwd='password', database='my_db')
cursor = database.cursor()
try:
cursor.execute("update Employee set name = 'alex' where id = 110")
cursor.commit()
except:
cursor.rollback()
cursor.close()
commit if the update will succeed otherwise rollback if got any error at the database level
or you can pass autocommit=True when you connect with database it will work too it's global configuration it will commit of some interval of time
like
database = mysql.connector.connect(host='localhost', user='root', passwd='password', database='my_db', autocommit=True)
cursor = database.cursor()

How can I sort a database by date?

I am creating a Python app that will store my homework in a database (using PhpMyAdmin). Here comes my problem:
At this moment, I am sorting every input with an ID (1, 2, 3, 4...), a date (23/06/2018...), and a task (read one chapter of a book). Now I would like to sort them by the date because when I want to read what do I have to do. I would prefer to see what shall I do first, depending on when should I get it done. For example:
If I have two tasks: one 25/07/2018 and the other 11/07/2018, I would like to show the 11/07/2018 first, no matter if it was addead later than the 25/07/2018. I am using Python (3.6), pymysql and PhpMyAdmin to manage the database.
I have had an idea to get this working, maybe I could run a Python script every 2 hours, that sorts all the elements in the database, but I have no clue about how can I do it.
Now, I will show you the code that enters the values into a database and then it shows them all.
def dba():
connection = pymysql.connect(host='localhost',
user='root',
password='Adminhost123..',
db='deuresc',
charset='utf8mb4',
cursorclass=pymysql.cursors.DictCursor)
try:
with connection.cursor() as cursor:
# Create a new record
sql = "INSERT INTO `deures` (`data`, `tasca`) VALUES (%s, %s)"
cursor.execute(sql, (data, tasca))
# connection is not autocommit by default. So you must commit to save
# your changes.
connection.commit()
with connection.cursor() as cursor:
# Read a single record
sql = "SELECT * FROM `deures` WHERE `data`=%s"
cursor.execute(sql, (data,))
resultat = cursor.fetchone()
print('Has introduït: ' + str(resultat))
finally:
connection.close()
def dbb():
connection = pymysql.connect(host='localhost',
user='root',
password='Adminhost123..',
db='deuresc',
charset='utf8mb4',
cursorclass=pymysql.cursors.DictCursor)
try:
with connection.cursor() as cursor:
# Read a single record
sql = "SELECT * FROM `deures`"
cursor.execute(sql)
resultat = cursor.fetchall()
for i in resultat:
print(i)
finally:
connection.close()
Can someone help?
You don't sort the database. You sort the results of the query when you ask for data. So in your dbb function you should do:
SELECT * FROM `deures` ORDER BY `data`
assuming that data is the field with the date.

I use python mysql API to insert data into mysql but it didn't work when i didn't add statement 'with conn:'

#!/usr/bin/python
#Program:
# insert data into mysql and the display them
import MySQLdb as mdb
conn = mdb.connect(host = 'localhost', user = 'root', passwd = '8023xue0526', db ='contact')
cur = conn.cursor()
cur.execute("insert into contact values('123221', 'ni')")
cur.execute("select * from contact")
row_num = int(cur.rowcount)
for i in range(row_num):
row = cur.fetchone()
print row
I use those code to insert a data into mysql, the program worked. but after that, i check it in mysqlclient, the data didn't exist.
But when I add a statement 'with conn:' before 'cur = conn.cursor(), the data really insert into mysql. the code like this
#!/usr/bin/python
#Program:
# to get some information from mysql
import MySQLdb as mdb
import sys
conn = mdb.connect(host = 'localhost', user = 'root', passwd = '8023xue0526', db = 'contact')
with conn:
cur = conn.cursor()
cur.execute("insert into contact values('122221', 'ni')")
cur.execute("select * from contact")
row_num = int(cur.rowcount)
for i in range(row_num):
row = cur.fetchone()
print row
with conn: (using the connection object as a context manager) ensures that the transaction is committed if no exceptions occurred within the code block governed by the with statement.
Without the context manager, use conn.commit() to explicitly commit the transaction.
Martijn Pieters answer is the right one. Just to develop a little bit more, you have to understand that databases are designated both with "concurrent access" and "possibility of failure" in mind.
In that case, is would be unacceptable if someone started to make changes to the DB, showing that (incomplete) changes to other DB users, and suddenly, for some reason (bug, kill, etc.) aborting its modifications thus leaving the DB in an inconsistent state.
To prevent that, when your DB run in a decent isolation level you have to explicitly state that your changes are ready to publish. That is the purpose of the commit statement.
In Python you either have to explicitly call conn.commit()yourself. Or let the context manager with conn: do it for you if there is no exception. The two fragments below does globally the same thing:
>>> with conn:
... c = conn.cursor()
... c.doSomething()
... # implicit commit here
>>> conn = sqlite3.connect(....)
>>> c = conn.cursor()
>>> c.doSomething()
>>> conn.commit() # explicit commit here
Please note that, in either cases, the commit operation might fail. For example, if a concurrent transaction has already committed incompatible changes to the database.

How to retrieve table names in a mysql database with Python and MySQLdb?

I have an SQL database and am wondering what command you use to just get a list of the table names within that database.
To be a bit more complete:
import MySQLdb
connection = MySQLdb.connect(
host = 'localhost',
user = 'myself',
passwd = 'mysecret') # create the connection
cursor = connection.cursor() # get the cursor
cursor.execute("USE mydatabase") # select the database
cursor.execute("SHOW TABLES") # execute 'SHOW TABLES' (but data is not returned)
now there are two options:
tables = cursor.fetchall() # return data from last query
or iterate over the cursor:
for (table_name,) in cursor:
print(table_name)
SHOW tables
15 chars
show tables will help. Here is the documentation.
It is also possible to obtain tables from a specific scheme with execute the single query with the driver below.
python3 -m pip install PyMySQL
import pymysql
# Connect to the database
conn = pymysql.connect(host='127.0.0.1',user='root',passwd='root',db='my_database')
# Create a Cursor object
cur = conn.cursor()
# Execute the query: To get the name of the tables from a specific database
# replace only the my_database with the name of your database
cur.execute("SELECT table_name FROM information_schema.tables WHERE table_schema = 'my_database'")
# Read and print tables
for table in [tables[0] for tables in cur.fetchall()]:
print(table)
output:
my_table_name_1
my_table_name_2
my_table_name_3
...
my_table_name_x

Categories

Resources