正如标题所述,我需要一些Python和MySQL方面的帮助。我目前正在进一步学习Python,我正在努力将Python和MySQL用于数据库设计、开发、管理和应用程序。
我对MySQL比较熟悉,对Python语言也比较熟悉。目前,我正在从事面向对象的编程,我正在尝试在数据库类中建立数据库连接,然后使用该类来创建、更新、删除和读取数据。
我创建了一个新的Python对象:
import pymysql as MySQL
class Database(object):
Host = "127.0.0.1"
Database = "****"
user = "****"
password = "****"
@staticmethod
def initialize():
currentdb = MySQL.connect(Database.Host, Database.user, Database.password, Database.Database)
cursor = currentdb.cursor()
@staticmethod
def insert(Table, DataDict):
placeholders = ", ".join(["%s"] * len(DataDict))
columns = ", ".join(DataDict.keys())
sql = "INSERT INTO %s (%s) VALUES (%s)"%(Table, columns, placeholders)
cursor.execute(sql, DataDict.values())
我想知道,如何在对象中使用光标?我不知道我目前的方法是否接近应该如何处理它,我真的不确定。
可以这样初始化游标,然后像我在上面的摘录中打算做的那样在对象中进一步使用游标吗?
任何帮助都将不胜感激。
发布于 2017-03-05 19:09:59
使用游标的正确方法如下所示:
import contextlib
def doSomething():
with contextlib.closing(database.cursor()) as cursor:
cursor.execute(...)
# At the end of the `with` statement, cursor is closed
不要让光标打开太长时间。就像您所做的那样,长时间地保持连接打开是很好的。另外,请阅读事务控制。
如果您要执行大量的DB操作,请考虑使用SQLAlchemy或Pony ORM之类的库。
发布于 2017-03-05 19:14:41
import contextlib
def doSomething():
with contextlib.closing(database.cursor()) as cursor:
cursor.execute(...)
db SQLAlchemy或Pony ORM的库。
发布于 2017-03-05 19:19:20
查看以下代码。我将initialize()中的内容添加到标准的python类init方法中,并使用不同类型的参数初始化数据库:
import pymysql as MySQL
class Database(object):
def __init__(self, host, db, user, pw):
self.currentdb = MySQL.connect(Database.host, user, pw, db)
def insert(self, Table, DataDict):
placeholders = ", ".join(["%s"] * len(DataDict))
columns = ", ".join(DataDict.keys())
sql = "INSERT INTO %s (%s) VALUES (%s)"%(Table, columns, placeholders)
with self.currentdb.cursor() as db_cursor:
db_cursor.execute(sql, DataDict.values())
一旦你在这里,然后你可以初始化一个数据库对象,如下所示,并插入数据:
my_db = Database(host="127.0.0.1", user="****", pw="****", db="****")
my_db.insert('table_name', data_dict)
请注意,我没有修改你的代码,只是根据你最初的帖子展示了一个可以工作的组织。
https://stackoverflow.com/questions/42612522
复制