如何使用python程序连接MySQL数据库?
当前回答
首先安装驱动程序(Ubuntu)
Sudo apt-get install python-pip sudo pip install -U pip Sudo apt-get install python-dev libmysqlclient-dev sudo apt-get install MySQL-python
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 ()
其他回答
首先安装驱动程序
pip install MySQL-python
然后一个基本代码是这样的:
#!/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
在终端上执行以下命令安装mysql connector:
pip install mysql-connector-python
在你的python编辑器中运行这个来连接MySQL:
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="username",
passwd="password",
database="database_name"
)
执行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, update, delete commands
更多命令:https://www.w3schools.com/python/python_mysql_getstarted.asp
Oracle (MySQL)现在支持纯Python连接器。这意味着不需要安装二进制文件:它只是一个Python库。它叫做“连接器/Python”。
http://dev.mysql.com/downloads/connector/python/
安装完成后,您可以在这里看到一些使用示例
对于Python3.6,我找到了两个驱动程序:pymysql和mysqlclient。我测试了它们之间的性能,得到的结果是:mysqlclient更快。
下面是我的测试过程(需要安装python lib profilehooks来分析时间流逝:
select * from FOO;
立即在mysql终端执行: set中有46410行(0.10秒)
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()
下面是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()
下面是mysqlclient的配置文件:
因此,mysqlclient似乎比pymysql快得多
你可以用这种方式连接你的python代码到mysql。
import MySQLdb
db = MySQLdb.connect(host="localhost",
user="appuser",
passwd="",
db="onco")
cursor = db.cursor()
推荐文章
- 将表从一个数据库复制到另一个数据库的最简单方法?
- 为什么我得到“'str'对象没有属性'读取'”当尝试使用' json。载入字符串?
- 不区分大小写的列表排序,没有降低结果?
- 排序后的语法(key=lambda:…)
- 在烧瓶中返回HTTP状态代码201
- 使用python创建一个简单的XML文件
- APT命令行界面式的yes/no输入?
- 如何打印出状态栏和百分比?
- 在Python中获取大文件的MD5哈希值
- 在Python格式字符串中%s是什么意思?
- 如何循环通过所有但最后一项的列表?
- 如何通过查询在MySQL中获得数据库结构?
- python用什么方法避免默认参数为空列表?
- ValueError: numpy。Ndarray大小改变,可能表示二进制不兼容。期望从C头得到88,从PyObject得到80
- Anaconda /conda -安装特定的软件包版本