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()
Related
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)
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)
After reading many thread here i didn't resolved my problem, my code works with a free database created in this website (freemysqlhosting.net), but it doesn't work with my own database on a hosting webiste. My code ('******' for privacy):
#!/usr/bin/python3
import pymysql
db = pymysql.connect("sql.******.it", "******", "******", "******")
cursor = db.cursor()
cursor.execute("SELECT * FROM users")
results = cursor.fetchall()
print(results)
db.close()
Here the error:
pymysql.err.OperationalError: (2003, "Can't connect to MySQL server on 'sql.******.it' ([Errno 101] Network is unreachable)")
From command line I would use ping, and then nc. I mean, just cut things to minimum, an check if that works. So first validate if host is valid, and your host can resolve it to IP. Next check if you can connect to that host, on provided port. Here is sample in python.
If I have to bet - I would say, you are missing port... Just double check all names, docs provided by the hosting.
Have you tried using mysql.connector? That's what I use maybe it will work
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
passwd="yourpassword"
)
mycursor = mydb.cursor()
mycursor.execute("SELECT * FROM customers")
myresult = mycursor.fetchall()
for x in myresult:
print(x)
Getting connection error in PyMYSQL:
Error
conn = pymysql.connect(host='127.0.0.1', port=3306, user='root', passwd='', db='pymysql')
AttributeError: 'module' object has no attribute 'connect'
code
import pymysql
conn = pymysql.connect(host='127.0.0.1', port=3306, user='root', passwd='', db='pymysql')
cur = conn.cursor()
cur.execute("SELECT Host,User FROM user")
print(cur.description)
print()
for row in cur:
print(row)
cur.close()
conn.close()
Use capital 'C' in pymysql.Connect.
conn = pymysql.Connect(host='127.0.0.1', port=3306, user='root', passwd='', db='pymysql')
The above statement should work. It worked for me!
You've called some other module "pymysql". Look for a file named "pymysql.py" and rename it, and remove any associated .pyc file.
The connection was successful in this code:
con=pymysql.connect('localhost','root','root','mydb27')
But now I am following this code:
connection = pymysql.connect(host='localhost',
user='root',
password='kanha#12345',
database='mydb23',
charset='utf8mb4')
cur1=connection.cursor()
cur1.execute("select * from emp where city='hyd'")
I had that error, due I named my py file as select.py. I don't know how you named it but you could try changing the name file.
I want to use the python MySQLdb to access a remote MySQL server with --local-infile flag in order to be able to load data from a local file. (as mentioned in this question Importing CSV to MySQL table returns an error #1148)
I use
db = MySQLdb.connect(host="127.0.0.1", port=3307, user="someuser", passwd="password", db="sql_db")
to create a database connection. How do I mimic mysql -u username -p dbname --local-infile using MySQLdb
I know this is late for the initial question, but if someone comes here looking for the same you can do this:
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="root",
passwd="",
allow_local_infile=True,
)
Here you can check the docs for aditional flags: https://dev.mysql.com/doc/connector-python/en/connector-python-connectargs.html
If you want to set it as a DB config rather than in the connection, you can do it like this:
mydb = mysql.connector.connect(
host="localhost",
user="root",
passwd="",
)
mycursor = mydb.cursor()
try:
command = "SET GLOBAL local_infile = 'ON';"
mycursor.execute(command)
except mysql.connector.errors.DatabaseError:
pass
You can put your DB configurations in to a local file, and then read it when using.
config.ini
[MySQL]
host=192.168.20.28
user=root
password=123456
db_name=ovp_global
charset=utf8
py code:
import MySQLdb
import ConfigParser
config = ConfigParser.ConfigParser()
config.readfp(open("config.ini", "r"))
def get_connection():
host = config.get('MySQL', 'host')
user = config.get('MySQL', 'user')
passwd = config.get('MySQL', 'password')
db = config.get('MySQL', 'db_name')
charset = config.get('MySQL', 'charset')
return MySQLdb.connect(host=host, user=user, passwd=passwd, db=db, charset=charset)