如何使用python程序连接MySQL数据库?
当前回答
尽管有以上所有答案,如果您不想预先连接到特定的数据库,例如,如果您仍然想创建数据库(!),您可以使用connection.select_db(数据库),如下所示。
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()
其他回答
这里有一种方法,使用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()
参考这里
首先安装驱动程序(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 ()
对于python 3.3
CyMySQL https://github.com/nakagami/CyMySQL
我在windows 7上安装了pip,只是 安装cymysql
(你不需要cython) 快速无痛
MySQLdb是最直接的方法。您可以在连接上执行SQL查询。时期。
我更喜欢使用强大的SQLAlchemy,这也是python化的。下面是一个与查询相关的教程,下面是一个关于SQLALchemy的ORM功能的教程。
在终端上执行以下命令安装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
推荐文章
- 将表从一个数据库复制到另一个数据库的最简单方法?
- 为什么我得到“'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 -安装特定的软件包版本