python数据库操作-MySQL,SQLite

MySQL

首先使用MySqldb模块的connect方法连接到MysSQL守护进程。connect方法将返回一个数据库连接。使用数据库连接的cursor方法可以获得当前数据库的游标。然后就可以使用游标的Execute方法执行SQL语句,完成对数据库的操作。操作结束调用close方法关闭游标和数据库连接。

    import MySQLdb  ##导入python Mysql相关库
    con = MySQLdb.connect(host='localhost',user='root',passwd='',db='testPython') ##创建数据库连接
    cur = con.cursor()  ##获取数据库游标
    cur.execute('insert into student (name,age,sex) values(\'jee\',21,\'F\')') ##执行添加sql
    r = cur.execute('delete from student where age = 20') ##添加删除sql
    con.commit() ##提交事务
    cur.execute('select * from student') ##执行查询sql
    r = cur.fetchall() ##获取数据
    print r
    cur.close() ##关闭游标
    con.close() ##关闭数据库连接

SQLite

首先导入sqlite3模块,由于SQLite不需要服务器,因此直接使用connect方法打开数据库即可。connect方法返回一个数据库连接对象,使用其cursor方法可以获得一个游标,然后对记录进行操作。在完成操作之后,使用close方法关闭游标和数据库连接。

    import sqlite3
    con = sqlite3.connect('python') ##创建数据库连接
    cur = con.cursor()      ##获取数据库游标
    cur.execute('insert into student (name,age,sex) values(\'jee\',21,\'F\')')  ##执行添加sql
    r = cur.execute('delete from student where age = 20')   ##添加删除sql
    con.commit() ##提交事务
    cur.execute('select * from student') ##执行查询sql
    r = cur.fetchall() ##获取数据
    print r

    cur.close() ##关闭游标
    con.close() ##关闭数据库连接
发布了38 篇原创文章 · 获赞 5 · 访问量 9086

猜你喜欢

转载自blog.csdn.net/zj382561388/article/details/47950567