Cant import mysql.connector in python - python

I've installed several types of this mysql-connector such as mysql-connector and mysql-connector-python and mysql-connector-rf.
But it keeps saying its not imported. And when im trying to install the mysql-connector-rf it comes with a big red error message.
This is the error code when im trying to run my test.py:
PS C:\Users\Oscar GP\OneDrive - Aalborg Universitet\GPRO\aau\gpro\mysql\opgaveark1> & "C:/Users/Oscar GP/AppData/Local/Programs/Python/Python38-32/python.exe" "c:/Users/Oscar GP/OneDrive -
Aalborg Universitet/GPRO/aau/gpro/mysql/opgaveark1/opgave1/test.py"
Traceback (most recent call last):
File "c:/Users/Oscar GP/OneDrive - Aalborg Universitet/GPRO/aau/gpro/mysql/opgaveark1/opgave1/test.py", line 1, in <module>
import mysql.connector
ModuleNotFoundError: No module named 'mysql'
PS C:\Users\Oscar GP\OneDrive - Aalborg Universitet\GPRO\aau\gpro\mysql\opgaveark1>
and the python file:
import mysql.connector
db = mysql.connector.connect (
host='localhost',
user='oscar',
pwd='password',
database='gpro1'
)
cursor = db.cursor (dictionary = True)
cursor.execute ("CREATE TABLE IF NOT EXISTS TestTable (id INTEGER)")
for i in range (0,100):
cursor.execute (f"INSERT INTO TestTable VALUE({i})")
db.commit ()

Related

ModuleNotFoundError: No module named 'mysql'12

I am running the following code but expected to get the records from the student table in test database.
Here is my code:
import mysql.connector
word = input("Enter a word in English and press Enter: ")
con = mysql.connector.connect(
user="root",
password = "root",
host="localhost",
database = "test"
)
cursor = con.cursor()
query = cursor.execute("SELECT * FROM student")
results = cursor.fetchall()
if results:
for result in results:
print(result[1])
else:
print("We couldn't find any results about that.")
And here is the result:
Traceback (most recent call last):
File "g:/python learning/mysqlconnector.py", line 1, in <module>
import mysql.connector
ModuleNotFoundError: No module named 'mysql'
try to use the command
pip install mysql-connector
in terminal or cmd()

How to create a table using python in a remote Heroku database?

I am really new to Python and Heroku. I am currently running the following build:
Windows 10
A postgre SQL database created on Heroku remotely. This is a free plan.
I want to create a table in the remote database. The code I am trying to execute is:
import os
import psycopg2
DATABASE_URL = os.environ['DATABASE_URL']
conn = psycopg2.connect(
DATABASE_URL,
sslmode="require",
host="xxx",
port="xxx",
user="xxx",
password="xxx",
database="xxx")
def main():
sql = """CREATE TABLE books
(
id SERIAL PRIMARY KEY,
ISBN Varchar NOT NULL,
Title Varchar NOT NULL,
Author Varchar NOT NULL,
Year Integer NOT NULL
);"""
conn.close()
if __name__ == '__main__':
main()
The error that I get is
Traceback (most recent call last):
File "import.py", line 12, in <module>
DATABASE_URL = os.environ['Database_URL']
File "C:\Users\xxx\AppData\Local\Programs\Python\Python37-32\lib\os.py", line 678, in __getitem__
raise KeyError(key) from None
KeyError: 'Database_URL
'
pip freeze output
Click==7.0
Flask==1.0.2
Flask-Session==0.3.1
itsdangerous==1.1.0
Jinja2==2.10
MarkupSafe==1.1.0
numpy==1.16.1
pandas==0.24.1
psycopg2==2.7.7
psycopg2-binary==2.7.7
python-dateutil==2.8.0
pytz==2018.9
six==1.12.0
SQLAlchemy==1.2.17
Werkzeug==0.14.1

Python - AttributeError: module 'mysql' has no attribute 'connector'

I am newbie in case of python, i am using python 3.6 and mysql connecter from mysql website
pip install --allow-external mysql-connector-python mysql-connector-python
Everything was going good. I tried 3 examples from mysql website
Create DB and table , insert, select.
But after 2nd example it stops working and giving a error
Traceback (most recent call last):
File "select.py", line 3, in <module>
import mysql.connector
File "C:\Users\preet\AppData\Local\Programs\Python\Python36\lib\site-packages\
mysql\connector\__init__.py", line 37, in <module>
from .connection import MySQLConnection
File "C:\Users\preet\AppData\Local\Programs\Python\Python36\lib\site-packages\
mysql\connector\connection.py", line 45, in <module>
from .network import MySQLUnixSocket, MySQLTCPSocket
File "C:\Users\preet\AppData\Local\Programs\Python\Python36\lib\site-packages\
mysql\connector\network.py", line 28, in <module>
import socket
File "C:\Users\preet\AppData\Local\Programs\Python\Python36\lib\socket.py", li
ne 52, in <module>
import os, sys, io, selectors
File "C:\Users\preet\AppData\Local\Programs\Python\Python36\lib\selectors.py",
line 11, in <module>
import select
File "C:\Users\preet\Desktop\ptyhon-newspaper\select.py", line 7, in <module>
cnx = mysql.connector.connect(user='root', password='Jinqm21k',
AttributeError: module 'mysql' has no attribute 'connector'
Example code
from __future__ import print_function
from datetime import date, datetime, timedelta
import mysql.connector
cnx = mysql.connector.connect(user='root', password='****',
host='localhost',
database='worpress')
cursor = cnx.cursor()
query = ("SELECT first_name, last_name, hire_date FROM employees "
"WHERE hire_date BETWEEN %s AND %s")
hire_start = datetime.date(1999, 1, 1)
hire_end = datetime.date(1999, 12, 31)
cursor.execute(query, (hire_start, hire_end))
for (first_name, last_name, hire_date) in cursor:
print("{}, {} was hired on {:%d %b %Y}".format(
last_name, first_name, hire_date))
cursor.close()
cnx.close()
All examples stops working including create, insert, select
I unable to figure out what is wrong with it
Your issue was that mysql library was trying to import some packages which imports "select" package which was shadowed by your module "select.py". Please give an updated traceback what is not working now after renaming "select.py".
I also recommend you not to write code in the .py file itself, unless you want this code to be executed on module import. Create a routine instead and call it at __main__ section.
from __future__ import print_function
from datetime import date, datetime, timedelta
import mysql.connector
def print_employees():
cnx = mysql.connector.connect(user='root', password='Jinqm21k',
host='localhost',
database='worpress')
cursor = cnx.cursor()
...
if __name__ = '__main__':
print_employees()

NameError while handling command line arguments

I was trying out a few python test scripts with sqlite3.
Here is the script that I wrote
#!/usr/bin/env python
from sqlite3 import dbapi2 as sqlite
from sys import argv,exit
db_name = "filenames.db"
def define_db():
try:
conn = sqlite.connect(db_name)
except IOError as e:
print "problem while creating/connecting the db:",e.args[0]
exit(1)
return conn
def write_db(conn,cursor,fni):
conn.execute("CREATE TABLE IF NOT EXISTS file (filenames TEXT UNIQUE)")
query = "INSERT OR REPLACE INTO file VALUES($filenames)"
cursor.execute(query,[fni])
cursor.close()
conn.commit()
conn.close()
print fni,"should now be in the db"
exit(0)
if __name__ == "__main__":
if len(argv) == 2:
etag = argv[1]
else:
print "no argument given - stopping now"
exit(1)
conn = define_db()
cursor = conn.cursor()
write_db(conn,cursor,fni)
I keep getting this error and was not able to solve it.
Traceback (most recent call last):
File "blah.py", line 37, in <module>
write_db(conn,cursor,fni)
NameError: name 'fni' is not defined
Any idea what the problem is.
At this moment I use python 2.7.3
The last line of your script refers to a name fni that is not defined.
You have not defined the variable "fni", but you are using it.
Static analysis tools like pyflakes or pylint can be useful to catch silly errors like this
If you wrote the bulk of the code in a function (so it doesn't assume blub is a global variable, which don't make pyflakes/pylint complain):
def main():
if len(argv) == 2:
blub = argv[1]
else:
print "no argument given - stopping now"
exit(1)
conn = define_db()
cursor = conn.cursor()
write_db(conn,cursor,fni)
if __name__ == "__main__":
main()
...then you would get a pair of errors, which points out exactly what the error is (you stored the argument in blub, but tried to access it with fni):
$ pip install pyflakes
$ pyflakes example.py
example.py:30: local variable 'blub' is assigned to but never used
example.py:37: undefined name 'fni'

How connect to mysql with python via odbc

Im running mysql, pyodbc, python 2.7 loaded on Fedora 14 x64.
Odbcinst.ini is:
# Example driver definitions
# Driver from the postgresql-odbc package
# Setup from the unixODBC package
#[PostgreSQL]
#Description = ODBC for PostgreSQL
#Driver = /usr/lib/psqlodbc.so
#Setup = /usr/lib/libodbcpsqlS.so
#Driver64 = /usr/lib64/psqlodbc.so
#Setup64 = /usr/lib64/libodbcpsqlS.so
#FileUsage = 1
# Driver from the mysql-connector-odbc package
# Setup from the unixODBC package
[MySQL]
Description = ODBC for MySQL
#Driver = /usr/lib/libmyodbc5.so
#Setup = /usr/lib/libodbcmyS.so
Driver64 = /usr/lib64/libmyodbc5.so
Setup64 = /usr/lib64/libodbcmyS.so
FileUsage = 1
Odbc.ini is :
[MySQL]
Driver = MySQL
Database = mysql
Server = localhost
Socket = /var/lib/mysql/mysql.sock
User = rooter
Password = sshh
Mysql.sock is empty?
/var/lib/mysql/mysql.sock has 0.B
python script is:
import pyodbc
#pyodbc.pooling = False
conn = pyodbc.connect('DRIVER={MySQL};SOCKET=/var/lib/mysql/mysql.sock;UID=rooter;PWD=sshh')
csr = conn.cursor()
csr.execute("SET GLOBAL event_scheduler = ON")
csr.close()
conn.close()
del csr
I cant seem to connect with above script, Using isql i get Connected!
MyERROR msg:
Traceback (most recent call last):
File "/CCX/Py/MySql Event OFF.py", line 4, in <module>
conn = pyodbc.connect('DRIVER={MySQL};SOCKET=/var/lib/mysql/mysql.sock;UID=rooter;PWD=sshh')
pyodbc.Error: ('IM002', '[IM002] [unixODBC][Driver Manager]Data source name not found, and no default driver specified (0) (SQLDriverConnectW)')
On Win XPx64,
#cxn = MySQLdb.connect (host = "localhost",user="rooter",passwd ="sshh")
Err Msg:
File "C:\Python26\lib\site-packages\MySQLdb\__init__.py", line 19, in <module>
import _mysql
ImportError: DLL load failed: %1 is not a valid Win32 application.
Comparing odbcinst.ini and your odbc.ini show an odd value for driver in odbc.ini, you should have a dynamic library here (I think).
And why don't you use direct mysql connection (without odbc)? :
import _mysql
conn = _mysql.connect(host="localhost", user="rooter",
password="sshh", db="mysql")
conn.query("SET GLOBAL event_scheduler = ON")
conn.close()
(not tested)
File "C:\Python26\lib\site-packages\MySQLdb__init__.py", line 19, in
import _mysql
ImportError: DLL load failed: %1 is not a valid Win32 application.
if Python26 && windows
we need download 3 files : libguide40.dll, libmmd.dll, libmySQL.dll
put the 3 files to C:\Python26\Lib\site-packages
and also put the 3 files to C:\Windows\system32
then restart your system
if Python27 && windows
when you setup the module ,be careful the version
MySQL-python-1.2.3.win32-py2.7.exe
MySQL-python-1.2.4.win32-py2.7.exe
one of the 2 version is you need
source: http://mysql-python.sourceforge.net/MySQLdb.html#some-mysql-examples
code tested:
import _mysql
conn=_mysql.connect(host="localhost", user="root", passwd="***", db="test")
conn.query("select * from test_table")
result = conn.use_result()
print result.fetch_row()
The fetch_row() function has two parameters:
maxrows limits the max number of rows returned.
how: it returns a tuple when how=0 and returns a dictionary when how=1.
For example, result.fetch(maxrows=5, how=1) returns an array (maximum size: 5) of dictionaries where the key is the column name and the value is the column value.

Categories