pymysql
python第三方库,可以是实现对MySQL数据库的操作。
安装:
创建MySQL的数据库链接
示例代码:
1 2 3 4 5 6 7 8 9
| from pymysql import Connection conn = Connection( host = "localhost", port = 3306, user = 'root', password = `123456`, ) print(conn.get_server_info()) conn.close()
|
执行SQL语句
示例代码:
1 2 3 4 5 6 7 8 9 10 11
| from pymysql import Connection conn = Connection( host = "localhost", port = 3306, user = 'root', password = `123456`, ) cursor = conn.cursor() conn.select_db("test") cursor.execute("create table test_pymysql(id int, info varchar(255))") conn.close()
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| from pymysql import Connection conn = Connection( host = "localhost", port = 3306, user = 'root', password = `123456`, ) cursor = conn.cursor() conn.select_db("test") cursor.execute("select * from student") resulte: tuple = cursor.fetchall() for r in resulte: print(r) conn.close
|
如果需要确认数据提交:
则需要通过.commit()
方法确认提交
也可以设置自动commit属性来设置自动提交
示例代码:
1 2 3 4 5 6 7 8 9
| from pymysql import Connection conn = Connection( host = "localhost", port = 3306, user = 'root', password = `123456`, autocommit = True ) conn.commit()
|