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()
Related
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 ()
I am trying to connect a graph base to a project tiangolo/full-stack-fastapi-postgresql.
But every time I come across an import error.
Please tell me, maybe someone faced a similar problem.
Backend launch log:
Checking for script in /app/prestart.sh
Running script /app/prestart.sh
INFO:__main__:Initializing service
INFO:__main__:Starting call to '__main__.init', this is the 1st time calling it.
INFO:__main__:Service finished initializing
INFO [alembic.runtime.migration] Context impl PostgresqlImpl.
INFO [alembic.runtime.migration] Will assume transactional DDL.
Traceback (most recent call last):
File "/app/app/initial_data.py", line 1, in <module>
from app.dbase.init_db import init_db
File "/app/app/dbase/init_db.py", line 14, in <module>
from neomodel import db as neodb
File "/usr/local/lib/python3.7/site-packages/neomodel/__init__.py", line 3, in <module>
from .core import *
File "/usr/local/lib/python3.7/site-packages/neomodel/core.py", line 9, in <module>
from neomodel.util import Database, classproperty, _UnsavedNode, _get_node_properties
File "/usr/local/lib/python3.7/site-packages/neomodel/util.py", line 8, in <module>
from neo4j.v1 import GraphDatabase, basic_auth, CypherError, SessionError
ImportError: cannot import name 'CypherError' from 'neo4j.v1' (/usr/local/lib/python3.7/site-packages/neo4j/v1/__init__.py)
The code I was callin:
import logging
from sqlalchemy.orm import Session
from app import crud, schemas
from app.core.config import settings
from app.dbase import base
from neomodel import db as neodb
from neomodel import config, install_all_labels
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
def init_db(dbase: Session) -> None:
user = crud.user.get_by_email(dbase, email=settings.FIRST_SUPERUSER)
if not user:
user_in = schemas.UserCreate(
email=settings.FIRST_SUPERUSER,
password=settings.FIRST_SUPERUSER_PASSWORD,
is_superuser=True,
)
user = crud.user.create(dbase, obj_in=user_in)
neodb.set_connection("bolt://neo4j:password#neo4j:7687")
person = Profile(email=settings.FIRST_SUPERUSER)
person.save()
country = Country(name="Russia")
country.save()
person.country.connect(country)
The requirements for neomodel state that it requires neo4j 3.0, 3.1, 3.2, or 3.3
See the documentation: https://neomodel.readthedocs.io/en/latest/#requirements
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()
I'm trying to make a wrapper module for the RethinkDB API and I've come across an AttributeError when importing my class(called rethinkdb.py). I'm working in a virtual machine having a shared folder 'Github'.
I do this in IPython console:
import library.api.rethinkdb as re
This is the error:
Traceback (most recent call last):
File "", line 1, in
import library.api.rethinkdb as re
File "/media/sf_GitHub/library/api/rethinkdb.py", line 51,
in
conn = Connection().connect_to_database()
File "/media/sf_GitHub/library/api/rethinkdb.py", line 48,
in connect_to_database
raise e
AttributeError: 'module' object has no attribute 'connect'
This is the code:
import rethinkdb as r #The downloaded RethinkDB module from http://rethinkdb.com/
class Connection(object):
def __init__(self, host='127.0.0.1', port=28015, database=None, authentication_key=''):
self.host = host
self.port = port
if database is None:
self.db = 'test'
self.auth_key = authentication_key
def connect_to_database(self):
try:
conn = r.connect(self.host, self.port, self.db, self.auth_key)
except Exception, e:
raise e
return conn
conn = Connection().connect_to_database()
I ran into something similar today and I noticed the authors have changed basic behavior of the API in the later versions.
From what I have tested on my machine:
v2.3.0
import rethinkdb as r
r.connect()
v2.4.1
import rethinkdb as r
rdb = r.RethinkDB()
rdb.connect()
It worked for me when I ran:
import rethinkdb as rdb
r = rdb.RethinkDB()
r.connect('localhost', 28015).repl()
I have installed pysnmp-4.x.I am getting following error during running a SNMP program.
I am using pysnmpSE 3.5.2 now but getting same error. I found that pysnmpSE doesn't hav v4 module. I was suggested that following error should resolved if pySNMP SE 3.x is used.
Traceback (most recent call last):
File "C:\Documents and Settings\ggne0622\Desktop\Python\google-python-exercises\babynames\SimpleAgent.py", line 18, in <module>
from twistedsnmp import agent, agentprotocol, bisectoidstore
File "C:\Python27\Lib\site-packages\twistedsnmp\agent.py", line 4, in <module>
from twistedsnmp import datatypes
File "C:\Python27\Lib\site-packages\twistedsnmp\datatypes.py", line 7, in <module>
from twistedsnmp.pysnmpproto import v2c,v1
File "C:\Python27\Lib\site-packages\twistedsnmp\pysnmpproto.py", line 13, in <module>
from pysnmp.v4.proto.omni import v2c,v1, error, rfc1157, rfc1905
ImportError: No module named v4.proto.omni
Code:
#!/usr/bin/env python
from twisted.internet.iocpreactor import reactor
from twisted.internet import error as twisted_error
from twistedsnmp import agent, agentprotocol, bisectoidstore
#from twisted.internet import interfaces
try:
from twistedsnmp import bsdoidstore
except ImportError:
import warnings
warnings.warn( """No BSDDB OID Storage available for testing""" )
bsdoidstore = None
def createAgent( oids ):
ports = [161]+range(20000,25000)
for port in ports:
try:
`agentObject = reactor.IOCPReactor.listenUDP(port,` `agentprotocol.AgentProtocol(snmpVersion = 'v2c',agent = agent.Agent(dataStore =` `bisectoidstore.BisectOIDStore(OIDs = oids,),),),)`
`except twisted_error.CannotListenError:`
`pass`
`else:`
`return agentObject, port`
testingOIDs = {
'.1.3.6.1.2.1.1.1.0': 'Some tool out in the field',
'.1.3.6.1.2.1.1.2.0': '.1.3.6.1.4.1.88.3.1',
'.1.3.6.1.2.1.1.3.0': 558566090,
'.1.3.6.1.2.1.1.4.0': "support#somewhere.ca",
'.1.3.6.1.2.1.1.5.0': "NameOfSystem",
'.1.3.6.1.2.1.1.6.0': "SomeHeadEnd, West Hinterlands, Canada",
}
def main(oids=testingOIDs):
agent, port = createAgent( oids )
if __name__ == "__main__":
reactor.IOCPReactor.callWhenRunning( main )
reactor.IOCPReactor.run()
TwistedSNMP does not seem to be designed to work with PySNMP 4.x. Thus you should either use PySNMP 3.x / PySNMP SE or switch to PySNMP 4.x which has its own Twisted binding.