简体   繁体   English

如何连接到 Python 中的 MySQL 数据库?

[英]How do I connect to a MySQL Database in Python?

How do I connect to a MySQL database using a python program?如何使用 python 程序连接到 MySQL 数据库?

Connecting to MYSQL with Python 2 in three steps三步用Python 2连接MYSQL

1 - Setting 1 - 设置

You must install a MySQL driver before doing anything.在执行任何操作之前,您必须安装 MySQL 驱动程序。 Unlike PHP, Only the SQLite driver is installed by default with Python.与 PHP 不同,Python 默认仅安装 SQLite 驱动程序。 The most used package to do so is MySQLdb but it's hard to install it using easy_install.最常用的软件包是MySQLdb,但使用 easy_install 安装它很困难。 Please note MySQLdb only supports Python 2.请注意 MySQLdb 仅支持 Python 2。

For Windows user, you can get an exe of MySQLdb .对于 Windows 用户,您可以获得MySQLdbexe

For Linux, this is a casual package (python-mysqldb).对于 Linux,这是一个临时包 (python-mysqldb)。 (You can use sudo apt-get install python-mysqldb (for debian based distros), yum install MySQL-python (for rpm-based), or dnf install python-mysql (for modern fedora distro) in command line to download.) (您可以在sudo apt-get install python-mysqldb中使用sudo apt-get install python-mysqldb (适用于基于 debian 的发行版)、 yum install MySQL-python (适用于基于 rpm 的发行版)或dnf install python-mysql (适用于现代 Fedora 发行版)进行下载。)

For Mac, you can install MySQLdb using Macport .对于 Mac,您可以使用 Macport 安装 MySQLdb

2 - Usage 2 - 用法

After installing, Reboot.安装后,重启。 This is not mandatory, But it will prevent me from answering 3 or 4 other questions in this post if something goes wrong.这不是强制性的,但如果出现问题,它会阻止我在这篇文章中回答 3 或 4 个其他问题。 So please reboot.所以请重启。

Then it is just like using any other package :然后就像使用任何其他包一样:

#!/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()

Of course, there are thousand of possibilities and options;当然,有成千上万种可能性和选择; this is a very basic example.这是一个非常基本的例子。 You will have to look at the documentation.您将不得不查看文档。 A good starting point .一个好的起点

3 - More advanced usage 3 - 更高级的用法

Once you know how it works, You may want to use an ORM to avoid writing SQL manually and manipulate your tables as they were Python objects.一旦你知道它是如何工作的,你可能想要使用ORM来避免手动编写 SQL 并操作你的表,因为它们是 Python 对象。 The most famous ORM in the Python community is SQLAlchemy . Python 社区中最著名的 ORM 是SQLAlchemy

I strongly advise you to use it: your life is going to be much easier.我强烈建议您使用它:您的生活会轻松得多。

I recently discovered another jewel in the Python world: peewee .我最近发现了 Python 世界中的另一颗宝石: peewee It's a very lite ORM, really easy and fast to setup then use.这是一个非常精简的 ORM,设置和使用非常简单快捷。 It makes my day for small projects or stand alone apps, Where using big tools like SQLAlchemy or Django is overkill :它让我在小型项目或独立应用程序中度过了一天,在使用 SQLAlchemy 或 Django 等大型工具的情况下是过度的:

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

This example works out of the box.这个例子开箱即用。 Nothing other than having peewee ( pip install peewee ) is required.除了拥有 peewee ( pip install peewee ) 之外,什么都不需要。

Here's one way to do it, using MySQLdb , which only supports Python 2:这是使用MySQLdb的一种方法,它只支持 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()

Reference here 参考这里

If you do not need MySQLdb, but would accept any library, I would very, very much recommend MySQL Connector/Python from MySQL: http://dev.mysql.com/downloads/connector/python/ .如果您不需要 MySQLdb,但会接受任何库,我会非常非常推荐 MySQL 中的 MySQL Connector/Python: http : //dev.mysql.com/downloads/connector/python/

It is one package (around 110k), pure Python, so it is system independent, and dead simple to install.它是一个包(大约 110k),纯 Python,因此它与系统无关,并且安装非常简单。 You just download, double-click, confirm license agreement and go.您只需下载、双击、确认许可协议即可。 There is no need for Xcode, MacPorts, compiling, restarting …无需Xcode、MacPorts、编译、重启……

Then you connect like:然后你像这样连接:

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()

Oracle (MySQL) now supports a pure Python connector. Oracle (MySQL) 现在支持纯 Python 连接器。 That means no binaries to install: it's just a Python library.这意味着不需要安装二进制文件:它只是一个 Python 库。 It's called "Connector/Python".它被称为“连接器/Python”。

http://dev.mysql.com/downloads/connector/python/ http://dev.mysql.com/downloads/connector/python/

After installations, you can see some usage examples here安装后,您可以在这里看到一些使用示例

Stop Using MySQLDb if you want to avoid installing mysql headers just to access mysql from python.如果您想避免安装 mysql 头文件只是为了从 python 访问 mysql,请停止使用 MySQLDb。

Use pymysql .使用pymysql It does all of what MySQLDb does, but it was implemented purely in Python with NO External Dependencies .它完成 MySQLDb 所做的所有事情,但它纯粹是用 Python 实现的,没有外部依赖关系 This makes the installation process on all operating systems consistent and easy.这使得所有操作系统上的安装过程一致且简单。 pymysql is a drop in replacement for MySQLDb and IMHO there is no reason to ever use MySQLDb for anything... EVER! pymysqlpymysql替代品,恕我直言,没有理由将 MySQLDb 用于任何事情......永远! - PTSD from installing MySQLDb on Mac OSX and *Nix systems , but that's just me. - PTSD from installing MySQLDb on Mac OSX and *Nix systems ,但这只是我。

Installation安装

pip install pymysql

That's it... you are ready to play.就是这样......你准备好玩了。

Example usage from pymysql Github repo来自 pymysql Github 存储库的示例用法

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, ('webmaster@python.org', '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, ('webmaster@python.org',))
        result = cursor.fetchone()
        print(result)
finally:
    connection.close()

ALSO - Replace MySQLdb in existing code quickly and transparently还 - 快速透明地替换现有代码中的 MySQLdb

If you have existing code that uses MySQLdb, you can easily replace it with pymysql using this simple process:如果您有使用 MySQLdb 的现有代码,则可以使用以下简单过程轻松将其替换为 pymysql:

# import MySQLdb << Remove this line and replace with:
import pymysql
pymysql.install_as_MySQLdb()

All subsequent references to MySQLdb will use pymysql transparently.所有后续对 MySQLdb 的引用都将透明地使用 pymysql。

Try using MySQLdb .尝试使用MySQLdb MySQLdb only supports Python 2. MySQLdb 仅支持 Python 2。

There is a how to page here: http://www.kitebird.com/articles/pydbapi.html这里有一个如何分页: http : //www.kitebird.com/articles/pydbapi.html


From the page:从页面:

# 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 ()

As a db driver, there is also oursql .作为db驱动,还有oursql Some of the reasons listed on that link, which say why oursql is better:该链接上列出的一些原因,说明了为什么 oursql 更好:

  • oursql has real parameterization, sending the SQL and data to MySQL completely separately. oursql具有真正的参数化,将SQL和数据完全分开发送到MySQL。
  • oursql allows text or binary data to be streamed into the database and streamed out of the database, instead of requiring everything to be buffered in the client. oursql 允许文本或二进制数据流入数据库并流出数据库,而不是要求所有内容都在客户端进行缓冲。
  • oursql can both insert rows lazily and fetch rows lazily. oursql 既可以懒惰地插入行,也可以懒惰地取行。
  • oursql has unicode support on by default.默认情况下,oursql 支持 unicode。
  • oursql supports python 2.4 through 2.7 without any deprecation warnings on 2.6+ (see PEP 218) and without completely failing on 2.7 (see PEP 328). oursql 支持 python 2.4 到 2.7,在 2.6+ 上没有任何弃用警告(参见 PEP 218),并且在 2.7 上没有完全失败(参见 PEP 328)。
  • oursql runs natively on python 3.x. oursql 在 python 3.x 上本地运行。

So how to connect to mysql with oursql?那么如何用oursql连接mysql呢?

Very similar to mysqldb:与 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]

The tutorial in the documentation is pretty decent. 文档中教程相当不错。

And of course for ORM SQLAlchemy is a good choice, as already mentioned in the other answers.当然,正如其他答案中已经提到的,对于 ORM SQLAlchemy 是一个不错的选择。

Run this command in your terminal to install mysql connector:在终端中运行此命令以安装 mysql 连接器:

pip install mysql-connector-python

And run this in your python editor to connect to MySQL:并在您的 python 编辑器中运行它以连接到 MySQL:

import mysql.connector

mydb = mysql.connector.connect(
      host="localhost",
      user="yusername",
      passwd="password",
      database="database_name"
)

Samples to execute MySQL Commands (in your python edior):执行 MySQL 命令的示例(在您的 python 编辑器中):

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

For more commands: https://www.w3schools.com/python/python_mysql_getstarted.asp更多命令: https : //www.w3schools.com/python/python_mysql_getstarted.asp

SqlAlchemy Sqlalchemy


SQLAlchemy is the Python SQL toolkit and Object Relational Mapper that gives application developers the full power and flexibility of SQL. SQLAlchemy 是 Python SQL 工具包和对象关系映射器,可为应用程序开发人员提供 SQL 的全部功能和灵活性。 SQLAlchemy provides a full suite of well known enterprise-level persistence patterns, designed for efficient and high-performing database access, adapted into a simple and Pythonic domain language. SQLAlchemy 提供了一整套众所周知的企业级持久性模式,专为高效和高性能的数据库访问而设计,并适用于简单的 Pythonic 域语言。

Installation安装

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 way ORM方式

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()

Despite all answers above, in case you do not want to connect to a specific database upfront, for example, if you want to create the database still (!), you can use connection.select_db(database) , as demonstrated in the following.尽管上面有所有答案,但如果您不想预先连接到特定的数据库,例如,如果您仍然想创建数据库 (!),您可以使用connection.select_db(database) ,如下所示。

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()

Best way to connect to MySQL from python is to Use MySQL Connector/Python because it is official Oracle driver for MySQL for working with Python and it works with both Python 3 and Python 2.从 python 连接到 MySQL 的最佳方法是使用 MySQL Connector/Python,因为它是 MySQL 的官方 Oracle 驱动程序,用于使用 Python,并且它适用于 Python 3 和 Python 2。

follow the steps mentioned below to connect MySQL按照下面提到的步骤连接 MySQL

  1. install connector using pip使用 pip 安装连接器

    pip install mysql-connector-python

or you can download the installer from https://dev.mysql.com/downloads/connector/python/或者您可以从https://dev.mysql.com/downloads/connector/python/下载安装程序

  1. Use connect() method of mysql connector python to connect to MySQL.pass the required argument to connect() method.使用 mysql 连接器 python 的connect()方法连接到 MySQL。将所需的参数传递给connect()方法。 ie Host, username, password, and database name.即主机、用户名、密码和数据库名称。

  2. Create cursor object from connection object returned by connect() method to execute SQL queries.connect()方法返回的连接对象创建cursor对象以执行 SQL 查询。

  3. close the connection after your work completes.工作完成后关闭连接。

Example :示例

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()

Reference - https://pynative.com/python-mysql-database-connection/参考 - https://pynative.com/python-mysql-database-connection/

Important API of MySQL Connector Python MySQL 连接器 Python 的重要 API

  • For DML operations - Use cursor.execute() and cursor.executemany() to run query.对于 DML 操作 - 使用cursor.execute()cursor.executemany()来运行查询。 and after this use connection.commit() to persist your changes to DB并在此之后使用connection.commit()将您的更改保存到数据库

  • To fetch data - Use cursor.execute() to run query and cursor.fetchall() , cursor.fetchone() , cursor.fetchmany(SIZE) to fetch data获取数据 - 使用cursor.execute()运行查询和cursor.fetchall()cursor.fetchone()cursor.fetchmany(SIZE)以获取数据

Even though some of you may mark this as a duplicate and get upset that I am copying someone else's answer, I would REALLY like to highlight an aspect of Mr. Napik's response.尽管你们中的一些人可能会将此标记为重复,并且对我复制别人的答案感到不安,但我真的很想强调 Napik 先生的回应的一个方面。 Because I missed this, I caused nationwide website downtime (9min).因为我错过了这个,我造成了全国性的网站停机时间(9 分钟)。 If only someone shared this information, I could have prevented it!如果有人分享了这些信息,我本可以阻止它!

Here is his 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()

The important thing here is the Try and Finally clause.这里重要的是Tryfinally子句。 This allows connections to ALWAYS be closed, regardless of what happens in the cursor/sqlstatement portion of the code.这允许与始终关闭的连接,无论代码的游标/sqlstatement 部分发生了什么。 A lot of active connections cause DBLoadNoCPU to spike and could crash a db server.大量活动连接会导致 DBLoadNoCPU 飙升并可能导致数据库服务器崩溃。

I hope this warning helps to save servers and ultimately jobs!我希望这个警告有助于节省服务器和最终的工作! :D :D

MySQLdb is the straightforward way. MySQLdb是一种直接的方式。 You get to execute SQL queries over a connection.您可以通过连接执行 SQL 查询。 Period.时期。

My preferred way, which is also pythonic, is to use the mighty SQLAlchemy instead.我的首选方法也是 pythonic,是使用强大的SQLAlchemy Here is a query related tutorial, and here is a tutorial on ORM capabilities of SQLALchemy.这里是查询相关教程,这里是 SQLALchemy 的ORM 功能教程。

for Python3.6 I found two driver: pymysql and mysqlclient.对于 Python3.6,我找到了两个驱动程序:pymysql 和 mysqlclient。 I tested the performance between them and got the result: the mysqlclient is faster.我测试了它们之间的性能并得到了结果:mysqlclient 更快。

below is my test process(need install python lib profilehooks to analyze time elapse:下面是我的测试过程(需要安装python lib profilehooks来分析时间流逝:

raw sql: select * from FOO;原始 sql: select * from FOO;

immediatly execute in mysql terminal: 46410 rows in set (0.10 sec)立即在 mysql 终端中执行: 46410 rows in set (0.10 sec)

pymysql (2.4s): 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()

here's the pymysql profile:这是 pymysql 配置文件: 在此处输入图片说明


mysqlclient (0.4s) 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()

here's the mysqlclient profile:这是 mysqlclient 配置文件: 在此处输入图片说明

So, it seems that mysqlclient is much faster than pymysql所以,看来mysqlclient比pymysql快多了

Just a modification in above answer.只是对上述答案的修改。 Simply run this command to install mysql for python只需运行此命令即可为 python 安装 mysql

sudo yum install MySQL-python
sudo apt-get install MySQL-python

remember!记住! It is case sensitive.它区分大小写。

mysqlclient is the best as others only provide support to specific versions of python mysqlclient 是最好的,因为其他人只提供对特定版本的 python 的支持

 pip install mysqlclient

example code示例代码

    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())

see https://github.com/PyMySQL/mysqlclient-pythonhttps://github.com/PyMySQL/mysqlclient-python

Also take a look at Storm .也看看风暴 It is a simple SQL mapping tool which allows you to easily edit and create SQL entries without writing the queries.它是一个简单的 SQL 映射工具,可让您轻松编辑和创建 SQL 条目,而无需编写查询。

Here is a simple example:这是一个简单的例子:

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

To find and object use:要查找和对象使用:

michael = store.find(User, User.name == u"Michael").one()
print str(user.ID) # 10

Find with primary key:用主键查找:

print store.get(User, 1).name #Mark

For further information see the tutorial .有关更多信息,请参阅教程

This is Mysql DB connection这是 Mysql 数据库连接

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()

you can connect your python code to mysql in this way.您可以通过这种方式将您的 python 代码连接到 mysql。

import MySQLdb
db = MySQLdb.connect(host="localhost",
                 user="appuser",
                 passwd="",
                 db="onco")

cursor = db.cursor()

PyMySQL 0.10.1 - Released: Sep 10, 2020, has support for python3 as well. PyMySQL 0.10.1 - 发布时间:2020 年 9 月 10 日,也支持 python3。

python3 -m pip install PyMySQL

Simple 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)

output:输出:

(1, 'Petar', 'Petrovic', 1813, 'Njegusi')
(2, 'Donald', 'Tramp', 1946, 'New York')
(3, 'Bill', 'Gates', 1955, 'Seattle')

For python 3.3对于python 3.3

CyMySQL https://github.com/nakagami/CyMySQL CyMySQL https://github.com/nakagami/CyMySQL

I have pip installed on my windows 7, just pip install cymysql我在 Windows 7 上安装了 pip,只需 pip install cymysql

(you don't need cython) quick and painless (你不需要cython)快速无痛

first install the driver首先安装驱动

pip install MySQL-python   

Then a basic code goes like this:然后一个基本的代码是这样的:

#!/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 

First install the driver (Ubuntu)首先安装驱动程序(Ubuntu)

  • sudo apt-get install python-pip须藤 apt-get 安装 python-pip

  • sudo pip install -U pip须藤 pip install -U pip

  • sudo apt-get install python-dev libmysqlclient-dev sudo apt-get install python-dev libmysqlclient-dev

  • sudo apt-get install MySQL-python须藤 apt-get 安装 MySQL-python

MySQL database connection codes MySQL数据库连接代码

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 ()

First step to get The Library: Open terminal and execute pip install mysql-python-connector .获取库的第一步:打开终端并执行pip install mysql-python-connector After the installation go the second step.安装完成后进入第二步。

Second Step to import the library: Open your python file and write the following code: import mysql.connector第二步导入库:打开你的python文件并编写以下代码: import mysql.connector

Third step to connect to the server: Write the following code:第三步连接服务器:编写如下代码:

conn = mysql.connector.connect(host= you host name like localhost or 127.0.0.1 , username= your username like root , password = your password ) conn = mysql.connector.connect(host= you host name like localhost or 127.0.0.1 , username= your username like root , password = your password )

Third step Making the cursor: Making a cursor makes it easy for us to run queries.第三步制作游标:制作游标使我们可以轻松地运行查询。 To make the cursor use the following code: cursor = conn.cursor()要使光标使用以下代码: cursor = conn.cursor()

Executing queries: For executing queries you can do the following: cursor.execute(query)执行查询:要执行查询,您可以执行以下操作: cursor.execute(query)

If the query changes any thing in the table you need to add the following code after the execution of the query: conn.commit()如果查询更改了表中的任何内容,则需要在查询执行后添加以下代码: conn.commit()

Getting values from a query: If you want to get values from a query then you can do the following: cursor.excecute('SELECT * FROM table_name ') for i in cursor: print(i) #Or for i in cursor.fetchall(): print(i)从查询中获取值:如果要从查询中获取值,则可以执行以下操作: cursor.excecute('SELECT * FROM table_name ') for i in cursor: print(i) #Or for i in cursor.fetchall(): print(i)

The fetchall() method returns a list with many tuples that contain the values that you requested ,row after row . fetchall() 方法返回一个包含许多元组的列表,这些元组包含您请求的值,一行接一行。

Closing the connection: To close the connection you should use the following code: conn.close()关闭连接:要关闭连接,您应该使用以下代码: conn.close()

Handling exception: To Handel exception you can do it Vai the following method: try: #Logic pass except mysql.connector.errors.Error: #Logic pass To use a database: For example you are a account creating system where you are storing the data in a database named blabla, you can just add a database parameter to the connect() method ,like处理异常:对于 Handel 异常,您可以使用以下方法: try: #Logic pass except mysql.connector.errors.Error: #Logic pass使用数据库:例如,您是一个帐户创建系统,您将在其中存储blabla 数据库中的数据,您只需将数据库参数添加到 connect() 方法,例如

mysql.connector.connect(database = database name ) mysql.connector.connect(database =数据库名称)

don't remove other informations like host,username,password.不要删除主机、用户名、密码等其他信息。

如何使用python程序连接到MySQL数据库?

如果您只想从数据库中绘制一些数据,另一种选择是使用 Jupyter内核,它是为 MariaDB 设计的,但它也应该很容易在 MySQL 上工作。

Python does not come with an inbuilt Library to interact with MySQL, so in order to make a connection between the MySQL database and Python we need to install the MySQL driver or module for our Python Environment. Python does not come with an inbuilt Library to interact with MySQL, so in order to make a connection between the MySQL database and Python we need to install the MySQL driver or module for our Python Environment.

pip install mysql-connector-python

the mysql-connecter-python is an open source Python library that can connect your python code to the MySQL data base in a few lines of code. mysql-connecter-python 是一个开源 Python 库,可以通过几行代码将您的 python 代码连接到 MySQL 数据库。 And it is very compatible with the latest version of Python.并且与最新版本的Python非常兼容。

After install the mysql-connector-python, you can connect to your MySQL database using the the following code snippet.安装 mysql-connector-python 后,您可以使用以下代码片段连接到 MySQL 数据库。

import mysql.connector

Hostname = "localhost"
Username = "root"
Password ="admin"   #enter your MySQL password
 
#set connection
set_db_conn = mysql.connector.connect(host= Hostname, user=Username, password=Password)

if set_db_conn:
    print("The Connection between has been set and the Connection ID is:")
    #show connection id
    print(set_db_conn.connection_id)

Connect Django with MySQL将 Django 与 MySQL 连接

In Django, to connect your model or project to the MySQL data base, you need to install the mysqlclient library.在 Django 中,要将您的 model 或项目连接到 MySQL 数据库,您需要安装 mysqlclient 库。

pip install mysqlclient

And to configure your Django setting so your project can connect to the MySQL database, you can use the following setting.要配置您的 Django 设置,以便您的项目可以连接到 MySQL 数据库,您可以使用以下设置。

DATABASES = {
        'default': {
            'ENGINE': 'django.db.backends.mysql',
            'NAME': 'database_name',
            'USER': 'username',
            'PASSWORD': 'databasepassword@123',
            'HOST': 'localhost',   # Or an IP Address that your DB is hosted on
            'PORT': '3306',
            }

I have written a dedicated Python tutorial on my blog that covers how you can connect to a MySQL database and create tables using Python.我在我的博客上编写了专门的 Python 教程,其中介绍了如何连接到 MySQL 数据库并使用 Python 创建表。 To know more about it, click here .要了解更多信息, 请单击此处

Here's what I do, if the database doesn't exist yet, it creates for you:这就是我所做的,如果数据库还不存在,它会为你创建:

import sqlite3

conn = sqlite3.connect('data.db')
c = conn.cursor()

def create_table():
    c.execute('CREATE TABLE IF NOT EXISTS usersdata(idpedido INTEGER PRIMARY KEY ,cliente TEXT ,telefone TEXT ,prioridade TEXT ,data_entrada DATE ,data_prevista DATE ,horario_entrada TEXT , horario_saida TEXT , status TEXT)')


def add_data(idpedido,cliente,telefone,prioridade,data_entrada,data_prevista,horario_entrada,horario_saida,status):
    c.execute('INSERT INTO usersdata(idpedido,cliente,telefone,prioridade,data_entrada,data_prevista,horario_entrada,horario_saida,status ) VALUES (?,?,?,?,?,?,?,?,?)',(idpedido,cliente,telefone,prioridade,data_entrada,data_prevista,horario_entrada,horario_saida, status))
    conn.commit()

First, install python-mysql connector from https://dev.mysql.com/downloads/connector/python/首先,从https://dev.mysql.com/downloads/connector/python/安装 python-mysql 连接器

on Python console enter:在 Python 控制台上输入:

pip install mysql-connector-python-rf
import mysql.connector

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM