实现步骤:
一、使用mysql.connector
1、导入msql 的包
2、创建连接对象
3、使用cursor方法获取操作游标
4、fetchall方法获取数据,for循环进行输出
5、最后关闭连接对象
import mysql.connector
#创建连接对象
#参数分别为:ip地址,用户名,密码,库名
mydb=mysql.connector.connector(
host="192.168.139.128",
user="root",
passwd="root",
database="shops"
)
#使用cursor方法获取操作游标
cursor = mydb.cursor()
#使用execute方法执行一条sql语句
cursor.execute("select * from xxxtable")
#使用ferchall获取数据
data=cursor.fetchall()
for x in data:
print(x)
mydb.close
实现数据的插入
sql=""" insert into test(name,age) values("xxxname",23)"""
test = mydb.cursor()
test.execute(sql)#执行sql语句
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
二、pyMysql连接数据库
import pymysql
#参数分别为:ip,用户名,密码,库名
db=pymysql.connect("192.168.139.128","root","root","shops")
cursor=db.cursor()
cursor.execute("select * from goods limit 3")
result=cursor.fetchall()
for x in result:
print(x)
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9