如何使用python控制数据库?
程序员文章站
2022-04-04 20:27:18
1.安装MySQL数据库
MySQL官网下载
2.安装MySQL驱动
pip install mysql-connector-python --allow-exter...
1.安装MySQL数据库
MySQL官网下载
2.安装MySQL驱动
pip install mysql-connector-python --allow-external mysql-connector-python
3.连接数据库
#!/usr/bin/env python #coding=utf-8 import mysql.connector conn = mysql.connector.connect(user='root', password='huangxin', database='test') cursor = conn.cursor() # 创建user表: #cursor.execute('create table user (id varchar(20) primary key, name varchar(20))') # 插入一行记录,注意MySQL的占位符是%s: cursor.execute('insert into user (id, name) values (%s, %s)', ['1', 'Katy']) //插入第二条,cursor.execute('insert into user (id, name) values (%s, %s)', ['2', 'Bob']) # 提交事务: conn.commit() cursor.close()
在数据库中进行查询:
//在PyCharm中可运行下面的代码进行查询
#!/usr/bin/env python #coding=utf-8 import mysql.connector conn = mysql.connector.connect(user='root', password='huangxin', database='test') cursor = conn.cursor() cursor.execute('select * from user where id = %s', ('1',)) values = cursor.fetchall() print (values) # 关闭Cursor和Connection: cursor.close() conn.close()
运行结果:
"C:\Program Files\Python36\python.exe" C:/Users/Administrator/Desktop/jump_demo/test/test.py [('1', 'Katy')] [('2', 'Bob')] Process finished with exit code 0