如何使用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()
其他回答
这是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()
对于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快得多
这里有一种方法,使用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()
参考这里
首先安装驱动程序
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
去图书馆的第一步: 打开终端,执行pip install mysql-python-connector。 安装完成后进入第二步。
导入库的第二步: 打开你的python文件并编写以下代码: 进口mysql.connector
第三步连接服务器: 编写以下代码:
Conn = mysql.connector。连接(主机=您的主机名,如localhost或127.0.0.1, 用户名=您的用户名,如root, 密码=您的密码)
第三步制作光标: 使游标便于我们运行查询。 要使游标使用以下代码: Cursor = conn.cursor()
执行查询: 对于执行查询,您可以执行以下操作: cursor.execute(查询)
如果查询更改了表中的任何内容,则需要在执行查询后添加以下代码: conn.commit ()
从查询中获取值: 如果你想从查询中获取值,那么你可以做以下事情: 游标。execute ('SELECT * FROM table_name') for i in cursor: print(i) #或for i in cursor.fetchall(): print(i)
fetchall()方法逐行返回一个包含您请求的值的元组列表。
关闭连接: 要关闭连接,您应该使用以下代码: conn.close ()
处理例外: 要处理异常,你可以用下面的方法: try: #逻辑通过,mysql.connector.errors.Error: #逻辑通过 使用数据库: 例如,您是一个帐户创建系统,您将数据存储在名为blabla的数据库中,您只需向connect()方法添加一个数据库参数,如
mysql.connector。连接(database =数据库名)
不要删除主机、用户名、密码等其他信息。