Unknown Database Error python mysql - python

This link contains shows the database I've created in the mysql workbench and the connection I have established in the code but the database is unknown for some reason. Is there a step I've missed?
http://gyazo.com/d995c4da99043da43bfbd057a0a839c7
__author__ = 'avi'
from TwitterSearch import *
import json
twtsearch = TwitterSearch(
consumer_key='PXTUrlRfgC1zSTsAPU9z6EHtD',
consumer_secret='qM9F4FVj1qLFc6f795r96DQPNAJO8hkbWy4PXWYLfQcYyNGY7D',
access_token='2943116292-wVHEjbfjX7OFqaOURBqim5o7Vs6lZyjxsoto8nD',
access_token_secret='CJAppSRY9TZ5cwYTABZhH2YTd0rm5IzBDqPder6v4qLBA'
)
twtsearchorder = TwitterSearchOrder()
twtsearchorder.set_keywords(['iphone6'])
twtsearchorder.set_language('en')
twtsearchorder.set_include_entities(True)
tweet_limit=50
parsed_tweets= {}
table="twtinfo"
import MySQLdb as mdb
con = mdb.connect('localhost', 'root','root','tweetinfo')
cur=con.cursor()
for tweet in twtsearch.search_tweets_iterable(twtsearchorder):
if tweet_limit > 0 :
parsed_tweets['name'] = tweet['user']['screen_name']
parsed_tweets['content'] = tweet['text']
parsed_tweets['user_id'] = tweet['user']['id']
parsed_tweets['fav_count'] = tweet['favorite_count']
parsed_tweets['location'] = tweet['user']['location']
parsed_tweets['retweet_count'] = tweet['retweet_count']
placeholders= ', '.join(['%s'] *len(parsed_tweets))
columns = ', '.join(parsed_tweets.keys())
sql="INSERT into %s ( %s ) VALUES ( %s )" % (table, columns, placeholders)
cur.execute(sql,parsed_tweets.values())
tweet_limit -= 1

The MySQL process is complaining about the database you are trying to access, namely tweetinfo isn't existing. MySQL error 1049 is usually an indication of having to forgot to select a database, but you did as forth argument to mdb.connect()
Possible errors could be:
That you have several MySQL processes running, with the one with the proper database not being on the default MySQL port.
That somehow your database GUI application hasn't actually submitted your database and table to the MySQL process.
That MySQL isn't running? You would probably get a different error message for that, but it could be an idea to make sure it is just in case.
Just to check if your tables exists and that your database is in place, open a terminal and write the following commands:
mysql -u root -proot
use tweetinfo;
show create table twtinfo;
Another thing to try could be to ask the MySQL process about which database it thinks you are using. Try adding something like the following to your code:
cur.execute("SELECT DATABASE() FROM DUAL;")
print("Database is: %s.", cur.fetchone()[0])
I'm not a python programmer, so I'm not entirely confident that will work without some adjustments.
If none of this gave you a good lead, I'm not quite sure what's wrong.

Related

psycopg2.errors.UndefinedTable: [duplicate]

I'm trying to figure out why I can't access a particular table in a PostgreSQL database using psycopg2. I am running PostgreSQL 11.5
If I do this, I can connect to the database in question and read all the tables in it:
import psycopg2
try:
connection = psycopg2.connect(user = "postgres", #psycopg2.connect() creates connection to PostgreSQL database instance
password = "battlebot",
host = "127.0.0.1",
port = "5432",
database = "BRE_2019")
cursor = connection.cursor() #creates a cursor object which allows us to execute PostgreSQL commands through python source
#Print PostgreSQL version
cursor.execute("""SELECT table_name FROM information_schema.tables
WHERE table_schema = 'public'""")
for table in cursor.fetchall():
print(table)
The results look like this :
('geography_columns',)
('geometry_columns',)
('spatial_ref_sys',)
('raster_columns',)
('raster_overviews',)
('nc_avery_parcels_poly',)
('Zone5e',)
('AllResidential2019',)
#....etc....
The table I am interested in is the last one, 'AllResidential2019'
So I try to connect to it and print the contents by doing the following:
try:
connection = psycopg2.connect(user = "postgres",
#psycopg2.connect() creates connection to PostgreSQL database instance
password = "battlebot",
host = "127.0.0.1",
port = "5432",
database = "BRE_2019")
cursor = connection.cursor() #creates a cursor object which allows us to execute PostgreSQL commands through python source
cursor.execute("SELECT * FROM AllResidential2019;") #Executes a database operation or query. Execute method takes SQL query as a parameter. Returns list of result
record = cursor.fetchall()
print(record)
except (Exception, psycopg2.Error) as error:
print("Error while connecting to PostgreSQL: ", error)
And I get the following error:
Error while connecting to PostgreSQL: relation "allresidential2019" does not exist
LINE 1: SELECT * FROM AllResidential2019;
However, I can successfully connect and get results when attempting to connect to another table in another database I have (this works! and the results are the data in this table):
try:
connection = psycopg2.connect(user = "postgres", #psycopg2.connect() creates connection to PostgreSQL database instance
password = "battlebot",
host = "127.0.0.1",
port = "5432",
database = "ClimbingWeatherApp") . #different database name
cursor = connection.cursor()
cursor.execute("SELECT * FROM climbing_area_info ;")
record = cursor.fetchall()
print(record)
except (Exception, psycopg2.Error) as error:
print("Error while connecting to PostgreSQL: ", error)
I can't figure out why I can retrieve information from one table but not another, using exactly the same code (except names are changes). And I am also not sure how to troubleshoot this. Can anyone offer suggestions?
Your table name is case-sensitive and you have to close it in double quotes:
SELECT * FROM "AllResidential2019";
In Python program it may look like this:
cursor.execute('SELECT * FROM "AllResidential2019"')
or you can use the specialized module SQL string composition:
from psycopg2 import sql
# ...
cursor.execute(sql.SQL("SELECT * FROM {}").format(sql.Identifier('AllResidential2019')))
Note that case-sensitive Postgres identifiers (i.e. names of a table, column, view, function, etc) unnecessarily complicate simple matters. I would advise you not to use them.
Likely, the reason for your issue is Postgres' quoting rules which adheres to the ANSI SQL standard regarding double quoting identifiers. In your table creation, you likely quoted the table:
CREATE TABLE "AllResidential2019" (
...
)
Due to case sensitivity of at least one capital letter, this requires you to always quote the table when referencing the table. Do remember: single and double quotes have different meanings in SQL as opposed to being mostly interchangeable in Python.
SELECT * FROM "AllResidential2019"
DELETE FROM "AllResidential2019" ...
ALTER TABLE "AllResidential2019" ...
It is often recommended, if your table, column, or other identifier does not contain special characters, spaces, or reserved words, to always use lower case or no quotes:
CREATE TABLE "allresidential2019" (
...
)
CREATE TABLE AllResidential2019 (
...
)
Doing so, any combination of capital letters will work
SELECT * FROM ALLRESIDENTIAL2019
SELECT * FROM aLlrEsIdEnTiAl2019
SELECT * FROM "allresidential2019"
See further readings on the subject:
Omitting the double quote to do query on PostgreSQL
PostgreSQL naming conventions
Postgres Docs - 4.1.1. Identifiers and Key Words
Don’t use double quotes in PostgreSQL
What is the difference between single and double quotes in SQL?
I was facing the same error in Ubuntu. But in my case, I accidentally added the tables to the wrong database, which was in turn owned by the root postgres user instead of the new postgres user that I had created for my flask app.
I'm using a SQL file to create and populate the tables. This is the command that I used to be able to create these tables using a .sql file. This allows you to specify the owner of the tables as well as the database in which they should be created:
sudo -u postgres psql -U my_user -d my_database -f file.sql -h localhost
You will then be prompted for my_users's password.
sudo -u postgres is only necessary if you are running this from a terminal as a the root user. It basically runs the psql ... command as the postgres user.

How to properly organise the database calls with Python and MySQL?

I have a code like this:
import mysql.connector as mysql
from generate_records import generateRecords
devicesQuery = "CALL iot.sp_sensors_overview()"
try:
db = mysql.connect(
user = "username",
password = "password",
host = "hostname",
database="iot"
)
cursor = db.cursor(dictionary=True, buffered=True)
cursor.execute(devicesQuery)
for sensor in cursor:
generateRecords(sensor, db)
cursor.close()
except mysql.connector.Error as error:
print("Error:")
print(error)
else:
db.close()
The purpose of generateRecords function is obviously to generate records and run the INSERT query against the different table.
Seems like I do something wrong, because no matter what I trying, I getting different errors here, like mysql.connector.errors.OperationalError: MySQL Connection not available..
(upd) I also tried to change the code like it was suggested (see example bellow), with no luck - I still receiving the MySQL connection not available. error.
rows = cursor.fetchall()
cursor.close()
for sensor in rows:
cursor2 = db.cursor()
generateRecords(sensor, cursor2)
So, should I create a new connection within generateRecords function, or pass something different within it, or use some kind of different approach here?
Thank you!
Finally I found what was wrong. I'm used the query to call the stored procedure. Using the cursor.callproc("sp_sensors_overview") instead fixed my issue, and now I'm able to create the next cursor without errors.

Python: cx_Oracle cursor.execute() hangs on UPDATE query

I have looked at similar questions but nothing has worked for me so far
So here it is. I want to update my table through a python script. I'm using the module cx_oracle. I can execute a SELECT query but whenever I try to execute an UPDATE query, my program just hangs (freezes). I realize that I need to use cursor.commit() after cursor.execute() if I am updating a table but my code never gets past cursor.commit(). I have added a code snippet below that I am using to debug.
Any suggestions??
Code
import cx_Oracle
def getConnection():
ip = '127.0.0.1'
port = 1521
service_name = 'ORCLCDB.localdomain'
username = 'username'
password = 'password'
dsn = cx_Oracle.makedsn(ip, port, service_name=service_name) # (CONNECT_DATA=(SERVICE_NAME=ORCLCDB.localdomain)))
return cx_Oracle.connect(username, password, dsn) # connection
def debugging():
con = getConnection()
print(con)
cur = con.cursor()
print('Updating')
cur.execute('UPDATE EMPLOYEE SET LATITUDE = 53.540943 WHERE EMPLOYEEID = 1')
print('committing')
con.commit()
con.close()
print('done')
debugging()
**Here is the corresponding output: **
<cx_Oracle.Connection to username#(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=127.0.0.1)(PORT=1521))(CONNECT_DATA=(SERVICE_NAME=ORCLCDB.localdomain)))>
Updating
Solution
After a bit of poking around, I found the underlying cause! I had made changes to the table using Oracle SQL Developer but had not committed them, when the python script tried to make changes to the table it would freeze up because of this. To avoid the freeze, I committed my changes in oracle sql developer before running the python script and it worked fine!
Do you have any option to look in the database ? I mean , in order to understand whether is a problem of the python program or not, we need to check the v$session in the database to understand whether something is blocked.
select sid, event, last_call_et, status from v$session where sid = xxx
Where xxx is the sid of the session which has connected with python.
By the way, I would choose to commit explicitly after cursor execute
cur.execute('UPDATE EMPLOYEE SET LATITUDE = 53.540943 WHERE EMPLOYEEID = 1')
con.commit()
Hope it helps
Best

sqlite + python: cannot update record

I use sqlite3 with python. I can CRUD tables via command line.
I can also successfully select, insert and delete (!) records via python. However, when I (within the very same connection context) try to update I get the exception: "unable to open database file".
I am puzzled, any ideas?
PS: The tables were created via Django's manage.py syncdb if this is of any relevance.
PPS: I am running the code through CGI (granted all permissions to the file, that's why I can also add to the database)
Sorry missed the code:
sDb = 'this\is\my\db'
conn = sqlite3.connect( sDb )
cursor = conn.cursor()
# below works:
sSql = "insert into app_filestamp ( file_id, sFileStamp ) values ( 12, 'YYYYY' )"
# below raises the error
sSql = "update app_filestamp set sFileStamp='XXXXX' where id=13"
cursor.execute( sSql )
conn.commit()
conn.close()
"Solution"
This awkward behaviour (insert works, update not) did only happened on a Windows environment.
Thanks for all your input; since this is obviously no known issue I re-thought my approach and got rid of the need for CGI.
Bear with me that I did not further investigate the issue.

MySQL in Python

The purpose is to check if the email already exists in the database utilizing python and MySQLdb. I am using the variable mail to store the e-mail. The MySQL form is email. I have the code below:
if cursor.execute("select count(*) from registrants where email = " + "'"email2"'") == 0:
print "it doesn't exist!"
What is wrong with this statement or how can I go about doing this?
I hardly know where to start.
Just typing a string of SQL into a Python program doesn't somehow query the database. You actually have to open a database connection, instantiate a cursor, use that cursor to run the SQL, and fetch the result. All this is explained in the MySQLdb documentation.
Once you've done that, you'll still need to actually pass the email parameter from your form to the SQL statement, which you're not doing either.
well that won't work because that's just the mysql query string. You have to execute this query using a mysql client receive the results and the test. Using pymysql would be something like this:
import pymysql
connection = pymysql.connect(host,user,password,database)
cursor = connection.cursor()
cursor.execute("select count(*) from registrants where email = ?") #you need to replace the ? with some actual value or the query will fail
result = cur.fetchone()
if result[0]==0:
print "E-mail does not exist!"

Categories

Resources