Ejemplo 1: cómo conectarse a la base de datos mysql en python
import mysql.connector
cnx = mysql.connector.connect(user='scott', password='password',
host='127.0.0.1',
database='employees')
cnx.close()
Ejemplo 2: conectar python a mysql
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
password="yourpassword",
port = 8888, #for Mamp users
database='whatever db you want'
)
print(mydb)
Ejemplo 3: acceso a la base de datos mysql de python3
#!/usr/bin/python3
import pymysql
# Open database connection
db = pymysql.connect("localhost","testuser","test123","TESTDB" )
# prepare a cursor object using cursor() method
cursor = db.cursor()
# Drop table if it already exist using execute() method.
cursor.execute("DROP TABLE IF EXISTS EMPLOYEE")
# Create table as per requirement
sql = """CREATE TABLE EMPLOYEE (
FIRST_NAME CHAR(20) NOT NULL,
LAST_NAME CHAR(20),
AGE INT,
SEX CHAR(1),
INCOME FLOAT )"""
cursor.execute(sql)
# disconnect from server
db.close()
Ejemplo 4: conectividad python y mysql
import pymysql
############### CONFIGURE THIS ###################
# Open database connection
db = pymysql.connect("database_host","username","password","database_name")
##################################################
# prepare a cursor object using cursor() method
cursor = db.cursor()
# execute SQL query using execute() method.
cursor.execute("SELECT VERSION()")
# Fetch a single row using fetchone() method.
data = cursor.fetchone()
print ("Database version : {0}".format(data))
# disconnect from server
db.close()
Ejemplo 5: Python de conexión mysql
from sqlalchemy import types, create_engine
import pymysql
try:
conn = create_engine('mysql+pymysql://user:[email protected]/database_name')
print("MySQL Connection Sucessfull!!!!!!!!!!!")
except Exception as err:
print("MySQL Connection Failed !!!!!!!!!!!")
print(err)
¡Haz clic para puntuar esta entrada!
(Votos: 0 Promedio: 0)