Python mysql 数据库操作

来源:互联网 发布:网络综合布线设计方案 编辑:程序博客网 时间:2024/05/24 00:55

Python操作数据库的方式相对来说比较简单,在这里简单总结一下常用的方式。

1.首先看最“原始”的方式,下面这段代码来自与w3cschool,更多增删改查的例子请点击这里:

import MySQLdb# 打开数据库连接db = MySQLdb.connect("localhost","testuser","test123","TESTDB" )# 使用cursor()方法获取操作游标 cursor = db.cursor()# SQL 插入语句sql = "INSERT INTO EMPLOYEE(FIRST_NAME, \       LAST_NAME, AGE, SEX, INCOME) \       VALUES ('%s', '%s', '%d', '%c', '%d' )" % \       ('Mac', 'Mohan', 20, 'M', 2000)try:    # 执行sql语句    cursor.execute(sql)    # 提交到数据库执行    db.commit()except:    # Rollback in case there is any error    db.rollback()finally:    # 关闭数据库连接    db.close()

但是这种方式每次都要关闭数据库的连接,而且有SQL注入的风险。



2.    使用with as方式,这样可以保证数据库的连接会在程序结束后自动关闭。

    with MySQLdb.connect(host=hostAdr, user=userName, passwd=password,db=database) as conn:        query = 'select column_name from information_schema.columns where table_name="%s"' % tableName        conn.execute(query)                results = conn.fetchall()      return results

这里的conn就是一个游标(cursor),但是这里面怎么使用rollback()操作我还不知道,希望知道的能回复我,谢了哈。但是这种方式也不能避免SQL注入的风险。


3.使用alchemy,这种方式应该是比较高大上的,也避免了SQL注入

mysql_db = create_engine('sqlite:///:memory:', pool_recycle=1900, pool_size=16, max_overflow=16,echo_pool=True) metadata = schema.MetaData(mysql_db)my_table = schema.Table('table', metadata, autoload=True)with mysql_db.connect() as connection:    trans = connection.begin()    try:        create_time_string=datetime.datetime.now().strftime("%H:%M,%Y-%m-%d")        ins = my_table.insert().values(user_id='one_of_list',tenant_id='hehe')                connection.execute(ins)                        trans.commit()    except:        trans.rollback()        raise        



0 0
原创粉丝点击