Hoe maak ik verbinding met een MySQL-database met behulp van een python-programma?
Antwoord 1, autoriteit 100%
In drie stappen verbinding maken met MYSQL met Python 2
1 – Instelling
U moet een MySQL-stuurprogramma installeren voordat u iets doet. In tegenstelling tot PHP wordt standaard alleen het SQLite-stuurprogramma met Python geïnstalleerd. Het meest gebruikte pakket hiervoor is MySQLdbmaar het is moeilijk om het te installeren met easy_install. Let op: MySQLdb ondersteunt alleen Python 2.
Voor Windows-gebruikers kun je een exe van MySQLdbkrijgen.
Voor Linux is dit een informeel pakket (python-mysqldb). (U kunt sudo apt-get install python-mysqldb
(voor op Debian gebaseerde distributies), yum install MySQL-python
(voor op rpm gebaseerde) of dnf install python-mysql
(voor moderne fedora distro) in de opdrachtregel om te downloaden.)
Voor Mac kunt u installeer MySQLdb met Macport.
2 – Gebruik
Na de installatie opnieuw opstarten. Dit is niet verplicht, maar het weerhoudt mij ervan om 3 of 4 andere vragen in dit bericht te beantwoorden als er iets misgaat. Dus start opnieuw op.
Dan is het net als elk ander pakket:
#!/usr/bin/python
import MySQLdb
db = MySQLdb.connect(host="localhost", # your host, usually localhost
user="john", # your username
passwd="megajonhy", # your password
db="jonhydb") # name of the data base
# you must create a Cursor object. It will let
# you execute all the queries you need
cur = db.cursor()
# Use all the SQL you like
cur.execute("SELECT * FROM YOUR_TABLE_NAME")
# print all the first cell of all the rows
for row in cur.fetchall():
print row[0]
db.close()
Natuurlijk zijn er duizenden mogelijkheden en opties; dit is een heel eenvoudig voorbeeld. Je zult de documentatie moeten bekijken. Een goed startpunt.
3 – Geavanceerder gebruik
Als je eenmaal weet hoe het werkt, wil je misschien een ORMgebruiken om handmatig SQL schrijven en uw tabellen manipuleren alsof het Python-objecten zijn. De meest bekende ORM in de Python-gemeenschap is SQLAlchemy.
Ik raad je ten zeerste aan om het te gebruiken: je leven wordt veel gemakkelijker.
Ik heb onlangs nog een juweel ontdekt in de Python-wereld: peewee. Het is een zeer lichte ORM, heel gemakkelijk en snel in te stellen en te gebruiken. Het maakt mijn dag goed voor kleine projecten of op zichzelf staande apps, waar het gebruik van grote tools zoals SQLAlchemy of Django overkill is:
import peewee
from peewee import *
db = MySQLDatabase('jonhydb', user='john', passwd='megajonhy')
class Book(peewee.Model):
author = peewee.CharField()
title = peewee.TextField()
class Meta:
database = db
Book.create_table()
book = Book(author="me", title='Peewee is cool')
book.save()
for book in Book.filter(author="me"):
print book.title
Dit voorbeeld werkt direct uit de doos. Niets anders dan peewee (pip install peewee
) is vereist.
Antwoord 2, autoriteit 15%
Hier is een manier om dit te doen, met behulp van MySQLdb, dat alleen Python 2:
#!/usr/bin/python
import MySQLdb
# Connect
db = MySQLdb.connect(host="localhost",
user="appuser",
passwd="",
db="onco")
cursor = db.cursor()
# Execute SQL select statement
cursor.execute("SELECT * FROM location")
# Commit your changes if writing
# In this case, we are only reading data
# db.commit()
# Get the number of rows in the resultset
numrows = cursor.rowcount
# Get and display one row at a time
for x in range(0, numrows):
row = cursor.fetchone()
print row[0], "-->", row[1]
# Close the connection
db.close()
Antwoord 3, autoriteit 10%
Als je MySQLdb niet nodig hebt, maar elke bibliotheek zou accepteren, zou ik MySQL Connector/Python van MySQL ten zeerste aanbevelen: http://dev.mysql.com/downloads/connector/python/.
Het is één pakket (ongeveer 110k), pure Python, dus het is systeemonafhankelijk en doodeenvoudig te installeren. Je hoeft alleen maar te downloaden, te dubbelklikken, de licentieovereenkomst te bevestigen en te gaan. Er is geen noodzaak voor Xcode, MacPorts, compileren, herstarten …
Vervolgens maak je verbinding als:
import mysql.connector
cnx = mysql.connector.connect(user='scott', password='tiger',
host='127.0.0.1',
database='employees')
try:
cursor = cnx.cursor()
cursor.execute("""
select 3 from your_table
""")
result = cursor.fetchall()
print result
finally:
cnx.close()
Antwoord 4, autoriteit 10%
Oracle (MySQL) ondersteunt nu een pure Python-connector. Dat betekent dat er geen binaire bestanden hoeven te worden geïnstalleerd: het is gewoon een Python-bibliotheek. Het heet “Connector/Python”.
http://dev.mysql.com/downloads/connector/python/
Na de installatie ziet u enkele gebruiksvoorbeelden hier
Antwoord 5, autoriteit 10%
Stop met het gebruik van MySQLDb als je wilt voorkomen dat je mysql-headers installeert om alleen maar toegang te krijgen tot mysql vanuit python.
Gebruik pymysql. Het doet alles wat MySQLDb doet, maar het is puur geïmplementeerd in Python met GEEN externe afhankelijkheden. Dit maakt het installatieproces op alle besturingssystemen consistent en eenvoudig. pymysql
is een vervanging voor MySQLDb en IMHO is er geen reden om ooit MySQLDb voor iets te gebruiken… OOIT! – PTSD from installing MySQLDb on Mac OSX and *Nix systems
, maar dat ben ik alleen.
Installatie
pip install pymysql
Dat is het… je bent klaar om te spelen.
Voorbeeld van gebruik van pymysql Github repo
import pymysql.cursors
import pymysql
# Connect to the database
connection = pymysql.connect(host='localhost',
user='user',
password='passwd',
db='db',
charset='utf8mb4',
cursorclass=pymysql.cursors.DictCursor)
try:
with connection.cursor() as cursor:
# Create a new record
sql = "INSERT INTO `users` (`email`, `password`) VALUES (%s, %s)"
cursor.execute(sql, ('[email protected]', 'very-secret'))
# connection is not autocommit by default. So you must commit to save
# your changes.
connection.commit()
with connection.cursor() as cursor:
# Read a single record
sql = "SELECT `id`, `password` FROM `users` WHERE `email`=%s"
cursor.execute(sql, ('[email protected]',))
result = cursor.fetchone()
print(result)
finally:
connection.close()
ook – Vervang MySQLDB in de bestaande code snel en transparant
Als u bestaande code hebt die MySQLDB gebruikt, kunt u het eenvoudig vervangen door PYMYSQL met behulp van dit eenvoudige proces:
# import MySQLdb << Remove this line and replace with:
import pymysql
pymysql.install_as_MySQLdb()
Alle volgende verwijzingen naar MySQLDB zullen PYMYSQL transparant gebruiken.
Antwoord 6, Autoriteit 2%
Probeer mysqldb . MySQLDB ondersteunt alleen Python 2.
Er is een pagina hier: http://www.kitebird.com/articles/ pydbapi.html
Vanaf de pagina:
# server_version.py - retrieve and display database server version
import MySQLdb
conn = MySQLdb.connect (host = "localhost",
user = "testuser",
passwd = "testpass",
db = "test")
cursor = conn.cursor ()
cursor.execute ("SELECT VERSION()")
row = cursor.fetchone ()
print "server version:", row[0]
cursor.close ()
conn.close ()
Antwoord 7
Als een DB-stuurprogramma is er ook OURSQL . Enkele redenen die op die link worden vermeld, die zeggen waarom OurSQL beter is:
- OURSQL heeft echte parameterisatie, het verzenden van de SQL en gegevens naar MySQL volledig afzonderlijk.
- OURSQL biedt tekst- of binaire gegevens in de database en gestreamd uit de database, in plaats van dat alles in de klant wordt gebufferd.
- OursQL kan beide rijen lui worden en rijen rijzeling ophalen.
- OURSQL heeft standaard Unicode-ondersteuning.
- OurSQL ondersteunt Python 2.4 tot en met 2.7 zonder enige afschrijvingswaarschuwingen op 2.6+ (zie PEP 218) en zonder volledig te falen op 2.7 (zie PEP 328).
- Oursql loopt native op Python 3.x.
Dus hoe u verbinding maakt met MySQL met OURSQL?
Zeer vergelijkbaar met MySQLDB:
import oursql
db_connection = oursql.connect(host='127.0.0.1',user='foo',passwd='foobar',db='db_name')
cur=db_connection.cursor()
cur.execute("SELECT * FROM `tbl_name`")
for row in cur.fetchall():
print row[0]
De Tutorial in de documentatie is behoorlijk fatsoenlijk.
En natuurlijk voor Orm Sqlalchemy is een goede keuze, zoals reeds vermeld in de andere antwoorden.
Antwoord 8
Voer deze opdracht in uw terminal uit om MySQL-connector te installeren:
pip install mysql-connector-python
Voer dit uit in uw Python-editor om verbinding te maken met MySQL:
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="yusername",
passwd="password",
database="database_name"
)
Monsters om MySQL-opdrachten (in uw Python Edior) uit te voeren:
mycursor = mydb.cursor()
mycursor.execute("CREATE TABLE customers (name VARCHAR(255), address VARCHAR(255))")
mycursor.execute("SHOW TABLES")
mycursor.execute("INSERT INTO customers (name, address) VALUES ('John', 'Highway 21')")
mydb.commit() # Use this command after insert or update
Voor meer commando’s: https://www.w3schools.com/python/python_mysql_getstarted.asp
Antwoord 9
SQLALCHEMY
SQLALCHEMMY is de Python SQL Toolkit en Object Relational Mapper dat
Geeft applicatieontwikkelaars de volledige kracht en flexibiliteit van SQL.
Sqlalchemy biedt een volledige reeks bekende enterprise-level
Persistentiepatronen, ontworpen voor efficiënt en hoogwaardig
Databasetoegang, aangepast in een eenvoudige en pythonische domeintaal.
Installatie
pip install sqlalchemy
RAW-query
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker, scoped_session
engine = create_engine("mysql://<user_name>:<password>@<host_name>/<db_name>")
session_obj = sessionmaker(bind=engine)
session = scoped_session(session_obj)
# insert into database
session.execute("insert into person values(2, 'random_name')")
session.flush()
session.commit()
ORM manier
from sqlalchemy import Column, Integer, String
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker, scoped_session
Base = declarative_base()
engine = create_engine("mysql://<user_name>:<password>@<host_name>/<db_name>")
session_obj = sessionmaker(bind=engine)
session = scoped_session(session_obj)
# Bind the engine to the metadata of the Base class so that the
# declaratives can be accessed through a DBSession instance
Base.metadata.bind = engine
class Person(Base):
__tablename__ = 'person'
# Here we define columns for the table person
# Notice that each column is also a normal Python instance attribute.
id = Column(Integer, primary_key=True)
name = Column(String(250), nullable=False)
# insert into database
person_obj = Person(id=12, name="name")
session.add(person_obj)
session.flush()
session.commit()
Antwoord 10
Ondanks alle antwoorden hierboven, als u niet vooraf verbinding wilt maken met een specifieke database, bijvoorbeeld als u de database nog steeds (!), wilt maken, kunt u connection.select_db(database)
, zoals hieronder wordt aangetoond.
import pymysql.cursors
connection = pymysql.connect(host='localhost',
user='mahdi',
password='mahdi',
charset='utf8mb4',
cursorclass=pymysql.cursors.DictCursor)
cursor = connection.cursor()
cursor.execute("CREATE DATABASE IF NOT EXISTS "+database)
connection.select_db(database)
sql_create = "CREATE TABLE IF NOT EXISTS "+tablename+(timestamp DATETIME NOT NULL PRIMARY KEY)"
cursor.execute(sql_create)
connection.commit()
cursor.close()
Antwoord 11
Beste manier om verbinding te maken met MySQL uit Python is om MySQL Connector / Python te gebruiken omdat het officieel Oracle-stuurprogramma is voor MySQL voor het werken met Python en het werkt met zowel Python 3 als Python 2.
Volg de onderstaande stappen om MySQL
aan te sluiten
-
Connector installeren met PIP
pip install mysql-connector-python
Of u kunt het installatieprogramma downloaden van https://dev.mySQL.com/downloads/ Connector / Python /
-
Gebruik
connect()
Methode van MySQL-connector Python om verbinding te maken met MySQL.Pass het vereiste argument voorconnect()
-methode aan. d.w.z. host, gebruikersnaam, wachtwoord en database. -
Maken
cursor
Object van verbindingsobject dat wordt geretourneerd doorconnect()
Method om SQL-query’s uit te voeren. -
Sluit de verbinding nadat uw werk is voltooid.
voorbeeld :
import mysql.connector
from mysql.connector import Error
try:
conn = mysql.connector.connect(host='hostname',
database='db',
user='root',
password='passcode')
if conn.is_connected():
cursor = conn.cursor()
cursor.execute("select database();")
record = cursor.fetchall()
print ("You're connected to - ", record)
except Error as e :
print ("Print your error msg", e)
finally:
#closing database connection.
if(conn.is_connected()):
cursor.close()
conn.close()
Referentie – https://pynative.com/python-mysql-database-connection/
Belangrijke API van MySQL Connector Python
-
Voor DML-bewerkingen – Gebruik
cursor.execute()
encursor.executemany()
om de query uit te voeren. en gebruik daarnaconnection.commit()
om uw wijzigingen in DB te behouden -
Gegevens ophalen – Gebruik
cursor.execute()
om de query uit te voeren encursor.fetchall()
,cursor.fetchone()
,cursor.fetchmany(SIZE)
om gegevens op te halen
Antwoord 12
Hoewel sommigen van jullie dit misschien als een duplicaat markeren en boos worden dat ik het antwoord van iemand anders kopieer, zou ik ECHTeen aspect van het antwoord van de heer Napik willen benadrukken. Omdat ik dit miste, veroorzaakte ik landelijke website-downtime (9min). Als iemand deze informatie had gedeeld, had ik het kunnen voorkomen!
Hier is zijn code:
import mysql.connector
cnx = mysql.connector.connect(user='scott', password='tiger',
host='127.0.0.1',
database='employees')
try:
cursor = cnx.cursor()
cursor.execute("""select 3 from your_table""")
result = cursor.fetchall()
print(result)
finally:
cnx.close()
Het belangrijkste hier is de clausule Tryen Eindelijk. Hierdoor kunnen verbindingen met ALTIJDworden gesloten, ongeacht wat er gebeurt in het cursor/sqlstatement-gedeelte van de code. Veel actieve verbindingen veroorzaken een piek in DBLoadNoCPU en kunnen een db-server laten crashen.
Ik hoop dat deze waarschuwing helpt om servers en uiteindelijk banen te redden! 😀
Antwoord 13
MySQLdbis de rechttoe rechtaan manier. U kunt SQL-query’s uitvoeren via een verbinding. Periode.
Mijn voorkeursmanier, die ook pythonisch is, is om in plaats daarvan de machtige SQLAlchemyte gebruiken. Hier is een query-gerelateerdetutorial, en hier is een tutorial over ORM-mogelijkhedenvan SQLALchemy.
Antwoord 14
voor Python3.6 vond ik twee stuurprogramma’s: pymysql en mysqlclient. Ik testte de prestaties tussen hen en kreeg het resultaat: de mysqlclient is sneller.
hieronder is mijn testproces (moet python lib profilehooks installeren om de verstreken tijd te analyseren:
raw sql: select * from FOO;
direct uitvoeren in mysql-terminal:
46410 rows in set (0.10 sec)
pymysql (2.4s):
from profilehooks import profile
import pymysql.cursors
import pymysql
connection = pymysql.connect(host='localhost', user='root', db='foo')
c = connection.cursor()
@profile(immediate=True)
def read_by_pymysql():
c.execute("select * from FOO;")
res = c.fetchall()
read_by_pymysql()
mysqlclient (0.4s)
from profilehooks import profile
import MySQLdb
connection = MySQLdb.connect(host='localhost', user='root', db='foo')
c = connection.cursor()
@profile(immediate=True)
def read_by_mysqlclient():
c.execute("select * from FOO;")
res = c.fetchall()
read_by_mysqlclient()
hier is het mysqlclient-profiel:
Het lijkt er dus op dat mysqlclient veel sneller is dan pymysql
Antwoord 15
Gewoon een wijziging in het bovenstaande antwoord.
Voer gewoon deze opdracht uit om mysql voor python te installeren
sudo yum install MySQL-python
sudo apt-get install MySQL-python
onthoud! Het is hoofdlettergevoelig.
Antwoord 16
mysqlclient is de beste omdat anderen alleen ondersteuning bieden voor specifieke versies van python
pip install mysqlclient
voorbeeldcode
import mysql.connector
import _mysql
db=_mysql.connect("127.0.0.1","root","umer","sys")
#db=_mysql.connect(host,user,password,db)
# Example of how to insert new values:
db.query("""INSERT INTO table1 VALUES ('01', 'myname')""")
db.store_result()
db.query("SELECT * FROM new1.table1 ;")
#new1 is scheme table1 is table mysql
res= db.store_result()
for i in range(res.num_rows()):
print(result.fetch_row())
Zie https://github.com/pymysql/mysqlclient-python
Antwoord 17
Neem ook een kijkje op storm . Het is een eenvoudige SQL-mapping-tool waarmee u eenvoudig SQL-vermeldingen kunt bewerken en maken zonder de query’s te schrijven.
Hier is een eenvoudig voorbeeld:
from storm.locals import *
# User will be the mapped object; you have to create the table before mapping it
class User(object):
__storm_table__ = "user" # table name
ID = Int(primary=True) #field ID
name= Unicode() # field name
database = create_database("mysql://root:password@localhost:3306/databaseName")
store = Store(database)
user = User()
user.name = u"Mark"
print str(user.ID) # None
store.add(user)
store.flush() # ID is AUTO_INCREMENT
print str(user.ID) # 1 (ID)
store.commit() # commit all changes to the database
Gebruik en objectgebruik:
michael = store.find(User, User.name == u"Michael").one()
print str(user.ID) # 10
Zoek met primaire sleutel:
print store.get(User, 1).name #Mark
Zie voor meer informatie de tutorial .
Antwoord 18
Dit is MySQL DB-verbinding
from flask import Flask, render_template, request
from flask_mysqldb import MySQL
app = Flask(__name__)
app.config['MYSQL_HOST'] = 'localhost'
app.config['MYSQL_USER'] = 'root'
app.config['MYSQL_PASSWORD'] = 'root'
app.config['MYSQL_DB'] = 'MyDB'
mysql = MySQL(app)
@app.route('/', methods=['GET', 'POST'])
def index():
if request.method == "POST":
details = request.form
cur = mysql.connection.cursor()
cur.execute ("_Your query_")
mysql.connection.commit()
cur.close()
return 'success'
return render_template('index.html')
if __name__ == '__main__':
app.run()
Antwoord 19
je kunt op deze manier je python-code verbinden met mysql.
import MySQLdb
db = MySQLdb.connect(host="localhost",
user="appuser",
passwd="",
db="onco")
cursor = db.cursor()
Antwoord 20
PyMySQL 0.10.1
– Uitgebracht: 10 september 2020, biedt ook ondersteuning voor python3.
python3 -m pip install PyMySQL
Eenvoudige code:
import pymysql
# Connect to the database
conn = pymysql.connect(host='127.0.0.1',user='root',passwd='root',db='fax')
# Create a Cursor object
cur = conn.cursor()
# Execute the query
cur.execute("SELECT * FROM fax.student")
# Read and print records
for row in cur.fetchall():
print(row)
uitvoer:
(1, 'Petar', 'Petrovic', 1813, 'Njegusi')
(2, 'Donald', 'Tramp', 1946, 'New York')
(3, 'Bill', 'Gates', 1955, 'Seattle')
Antwoord 21
Voor python 3.3
CyMySQL
https://github.com/nakagami/CyMySQL
Ik heb pip geïnstalleerd op mijn Windows 7, alleen
pip installeer cymysql
(u hebt geen cython nodig)
snel en pijnloos
Antwoord 22
Installeer eerst het stuurprogramma
pip install MySQL-python
Dan gaat een basiscode zo:
#!/usr/bin/python
import MySQLdb
try:
db = MySQLdb.connect(host="localhost", # db server, can be a remote one
db="mydb" # database
user="mydb", # username
passwd="mydb123", # password for this username
)
# Create a Cursor object
cur = db.cursor()
# Create a query string. It can contain variables
query_string = "SELECT * FROM MY_TABLE"
# Execute the query
cur.execute(query_string)
# Get all the rows present the database
for each_row in cur.fetchall():
print each_row
# Close the connection
db.close()
except Exception, e:
print 'Error ', e
Antwoord 23
Installeer eerst het stuurprogramma (ubuntu)
-
SUDO APT-GET INSTALLATE PYTHON-PIP
-
SUDO PIP INSTALLATE -U PIP
-
SUDO Apt-Get Install Python-Dev Libmysqlclient-dev
-
SUDO APT-GET INSTALLE MYSQL-PYTHON
MySQL Database-verbindingscodes
import MySQLdb
conn = MySQLdb.connect (host = "localhost",user = "root",passwd = "pass",db = "dbname")
cursor = conn.cursor ()
cursor.execute ("SELECT VERSION()")
row = cursor.fetchone ()
print "server version:", row[0]
cursor.close ()
conn.close ()
Antwoord 24
eerste stap om de bibliotheek te krijgen:
Open terminal en voer pip install mysql-python-connector
uit.
Ga na de installatie naar de tweede stap.
Tweede stap om de bibliotheek te importeren:
Open je python-bestand en schrijf de volgende code:
import mysql.connector
Derde stap om verbinding te maken met de server:
Schrijf de volgende code:
conn = mysql.connector.connect(host=
you host name like localhost or 127.0.0.1
,
gebruikersnaam=your username like root
,
wachtwoord =your password
)
Derde stap De cursor maken:
Door een cursor te maken, kunnen we gemakkelijk query’s uitvoeren.
Gebruik de volgende code om de cursor te maken:
cursor = conn.cursor()
query’s uitvoeren:
Voor het uitvoeren van query’s kunt u het volgende doen:
cursor.execute(query)
Als de query iets in de tabel verandert, moet u de volgende code toevoegen na het uitvoeren van de query:
conn.commit()
Waarden ophalen uit een query:
Als u waarden uit een query wilt halen, kunt u het volgende doen:
cursor.excecute('SELECT * FROM
tabelnaam') for i in cursor: print(i) #Or for i in cursor.fetchall(): print(i)
De methode fetchall() retourneert een lijst met veel tuples die de door u gevraagde waarden rij na rij bevatten.
Verbinding verbreken:
Gebruik de volgende code om de verbinding te sluiten:
conn.close()
Afhandeling uitzondering:
Voor Handel-uitzondering kun je het op de volgende manier doen:
try: #Logic pass except mysql.connector.errors.Error: #Logic pass
Om een database te gebruiken:
U bent bijvoorbeeld een systeem voor het maken van een account waarbij u de gegevens opslaat in een database met de naam blabla, u kunt gewoon een databaseparameter toevoegen aan de methode connect(), zoals
mysql.connector.connect(database =
databasenaam)
verwijder geen andere informatie zoals host,gebruikersnaam,wachtwoord.
Antwoord 25
Een andere optie als u alleen wat gegevens uit de database wilt plotten, is om de Jupyter kernelte gebruiken , het is ontworpen voor MariaDB, maar het zou ook gemakkelijk op MySQL moeten werken.
Antwoord 26
Installeer eerst de python-mysql-connector van https://dev.mysql.com/ downloads/connector/python/
voer op de Python-console het volgende in:
pip install mysql-connector-python-rf
import mysql.connector