Connect to MySQL database using python - python

So I am having a super hard time connecting to a local database using the python mysql.connector module.
So I am trying to connect using the highlighted connection. I use the password abcdefghijkl to log into the SQL environment. I am trying to connect to a database named flight_school.
My python script looks like so.
import mysql.connector
mydb = mysql.connector.connect("localhost", "root", "abcdefghijkl", "flight_school")
print(mydb.is_connected())
This above code in the arguments in the following order i.e.
hostname = localhost,
user = 'root',
password = 'abcdefghijkl', and
database name = 'flight_school'.
It's just not working. I get the following error.
I would really appreciate some advice, please.

Please read always the official documentation
Your cooenction stirng has to have this form(if you do it this way=
mydb = mysql.connector.connect(
host="localhost",
user="root",
passwd="testpaaword",
database="testdb"
)

Check out SQL-Alchemy module, works wonders from my experience.

Please read always the official documentation: https://dev.mysql.com/doc/connector-python/en/connector-python-connectargs.html
import mysql.connector
from mysql.connector import errorcode, MySQLConnection
try:
db_connection = MySQLConnection(user='root', password='', port='3306', database='your_database')
print("Database connection made!")
except mysql.connector.Error as error:
if error.errno == errorcode.ER_BAD_DB_ERROR:
print("Database doesn't exist")
elif error.errno == errorcode.ER_ACCESS_DENIED_ERROR:
print("User name or password is wrong")
else:
print(error)
else:
db_connection.close()
cursor = db_connection.cursor()
sql = ("commands")
cursor.execute(sql)

Related

Python update query in mariadb

I am trying to update my mariadb table via python code .While compile the query nothing happen in my database. please check below code and let me know where i made mistake in update function
import mariadb
connection= mariadb.connect(user="user1", database="db1", host="ippp" ,password="pass")
cursor= connection.cursor()
cursor.execute("UPDATE product_options_combinations SET quantity=5944 WHERE item_code ='31628'")
cursor.close()
connection.close()
Hello here I have a clean code example for you. How to update it.
import pymysql
# Create a connection object
# IP address of the MySQL database server
Host = "localhost"
# User name of the database server
User = "user"
# Password for the database user
Password = ""
database = "GFG"
conn = pymysql.connect(host=Host, user=User, password=Password, database)
# Create a cursor object
cur = conn.cursor()
query = f"UPDATE PRODUCT SET price = 1400 WHERE PRODUCT_TYPE = 'broadband'"
cur.execute(query)
#To commit the changes
conn.commit()
conn.close()
You just need to add connection.commit() to your code, but I recommend you use a parametrized SQL preferably with a list of tuples,more of which might be added if needed, along with cursor.executemany() as being more performant for DML statements such as
import mariadb
connection= mariadb.connect(user="user1",
password="pass",
host="ippp",
port=3306,
database="db1")
cursor= connection.cursor()
dml="""
UPDATE product_options_combinations
SET quantity=%s
WHERE item_code =%s
"""
val=[
(5944,'31628')
]
cursor.executemany(dml,val)
connection.commit()
cursor.close()
connection.close()
Are you sure that the connection is working properly?
Have you tried to implement a try and catch routine to print mariadb errors?
Something like this:
# Connect to MariaDB Platform
import mariadb
try:
conn = mariadb.connect(
user="user",
password="password",
host="xx.xx.xx.xx",
port=3306,
database="db_name"
)
except mariadb.Error as e:
print(f"Error connecting to MariaDB Platform: {e}")
sys.exit(1)

Problem putting using %s in a MySQL command

I'm trying to automate (by using python scripting) the ability to create a MySQL role, but for some reason I am unable to put my string variable into mysql command. This is what I've got so far:
#!/usr/bin/python3
import mysql.connector
from mysql.connector import errorcode
# Open database connection
try:
serverHostName='localhost'
userName='root'
passwd='password'
databaseName='mysql'
roleName='reader'
cnx = mysql.connector.connect(
host=serverHostName,
database=databaseName,
user=userName,
password=passwd)
cursor=cnx.cursor(prepared=True)
dropRole="""DROP ROLE IF EXISTS %s """
print(dropRole, roleName)
#cursor.execute(dropRole, roleName)
#cnx.commit()
except mysql.connector.Error as err:
if err.errno == errorcode.ER_ACCESS_DENIED_ERROR:
print("Something is wrong with your user name or password")
elif err.errno == errorcode.ER_BAD_DB_ERROR:
print("Database does not exist")
else:
print(err)
else:
cnx.close()
print("You have successfully disconnected from your MySQL database")
what comes out is the following:
DROP ROLE IF EXISTS %s reader
You have successfully disconnected from your MySQL database
If anyone can explain to me why %s and the reader is showing up in my print line that would be much appreciated.
You didn't call a formatting operator to subsitute roleName into the string, so it's just printing the format string. Use the % operator to perform formatting.
print(dropRole % roleName)

Python script unable to connect to MySQL db with no password

I am having a weird issue with my python script. My script has to connect to MySQL DB. This is the code:
try:
conn = MySQLdb.connect( user='root', host = 'localhost')
cursor = conn.cursor()
databases = cursor.fetchall()
cursor.close()
except Exception as e:
print e
when I run this script I have and error like:
(1045, "Access denied for user 'root'#'localhost' (using password: NO")
in the other hand, I can connect to MySQL just by entering MySQL (without password).
Why am I having this error with my python script when there is no password to root user?
Provide empty password
try this
conn = MySQLdb.connect( user='root', host = 'localhost', passwd='')
This should be the syntax. You should have the MySql connector for Python
import mysql.connector
cnx = mysql.connector.connect(user='root', password='',
host='127.0.0.1',
database='database_name')
cnx.close()
try this (inside the bloc try except)
import mysql.connector
conn = mysql.connector.connect(user='root', password='',host='localhost',
database='your_database_name')
conn.close()

Can't connect to mysql using python's mysql.connector

I'm using a Mac (OS 10.10.5), PyCharm, Python 3.5 and MySQL. MySQL has been working with PHP on the same machine. I'm trying to connect to it using Python and getting the error message:
enter code here2003: Can't connect to MySQL server on 'localhost::3306' (8 nodename nor servname provided, or not known)
Can someone list the diagnostic steps so I can correct the problem? Thanks, Doug
Below is the connection code:
import mysql.connector
from mysql.connector import errorcode
try:
cnn = mysql.connector.connect(
host="localhost:", # your host, usually localhost
user="root", # your username
password="root", # your password
database="bb_cards") # name of the data base
print("It Works!!")
except mysql.connector.Error as e:
if e.errno == errorcode.ER_ACCESS_DENIED_ERROR:
print("Something is wrong with username or Password")
elif e.errno == errorcode.ER_BAD_DB_ERROR:
print("Database Does not exist")
else:
print(e)
You have a colon where there shouldn't be one:
host="localhost:" # remove the : -> host="localhost"
127.0.0.1::3306 is not the same as 127.0.0.1:3306
There are somethings I make out from your code.
we can provide host="localhost" no semicolons. or we can provide a host/server value like 'host':'127.0.0.1:<port name>'
Check your port again to connect the database
We should always close the connection viz. cnn.close() when our task is complete.

Python - can't connect to database

I'm learning python , I'm trying to connect to database:
OS Ubuntu 13.04
I have running the apache and localhost
Im using eclipse pydev
I have installed the mysql connector downloaded from here:http://dev.mysql.com/downloads/connector/python/ (a .deb file)
I have installed the sudo apt-get install python-mysqldb
List item
This is my code (simple)(with proper indent):
#!/usr/bin/python
import MySQLdb
try:
db = MySQLdb.connect(host="localhost", # your host, usually localhost
user="root", # your username
passwd="root", # your password
db="Ayuda") # name of the data base
except Exception as a:
print a
cur = db.cursor()
cur.execute("SELECT * FROM YOUR_TABLE_NAME")
for row in cur.fetchall() :
print row[0]
So I get this error:
(2002, "Can't connect to local MySQL server through socket
'/var/run/mysqld/mysqld.sock' (2)")
How do I solve this?
I have resolved: I used another code taken from mysql example of use: http://dev.mysql.com/doc/connector-python/en/myconnpy_example_connecting.html
this is my code now:
import mysql.connector
from mysql.connector import errorcode
try:
cnx = mysql.connector.connect(host="localhost",
user="root",
passwd="root",
db="Ayuda")
except mysql.connector.Error as err:
if err.errno == errorcode.ER_ACCESS_DENIED_ERROR:
print("Something is wrong with your user name or password")
elif err.errno == errorcode.ER_BAD_DB_ERROR:
print("Database does not exists")
else:
print(err)
else:
cur = cnx.cursor()
cur.execute("SELECT * FROM mitabla")
for row in cur.fetchall() :
print row[1]
cnx.close()
I still don't know why I could'connect the other way.

Categories

Resources