安装库
安装pymysql
pip install pymysql
连接数据库
首先需要创建一个连接
import pymysql
connection = pymysql.connect(
host = 'localhost', # 132.423.543.234
port=3306,
user='root', # username
password='123',
db='collection_db',
charset='utf8'
host:数据库的ip地址,如果是在本地的话,那么可以为localhost,如果是在远程,那么需要输入远程计算机的ip地址。
port:端口地址,一般为3306,创建数据库的时候确定
user:登陆者信息,如果是本地,则为root,如果是在远程,则为创建数据库时已经注册过的用户名
password:登陆者密码,同样是注册时的密码
db:访问的数据库名称
charset:编码,一般为utf-8
查询数据库
# 创建一个游标,
cursor = connection.cursor()
sql = 'select 关键字1, 关键字2 from 表名称 where 限定条件'
try:
flag = cursor.execute(sql))
print(flag)
if flag:
data = cursor.fetchall()
print(data)
else:
print("获取数据失败")
except:
print("执行sql语句:{} 出错".format(sql))
首先创建一个游标,下面的操作就是使用该游标进行的。
然后创建一个sql语句,这里就和普通的sql语句是一样的,从表中取得满足条件的某些关键字。然后通过cursor.execute()函数执行该sql,如果执行成功,则返回值为1,否则返回0。
在查询的时候,如果需要动态传入数据,比如通过一个for循环传入限定条件等,则可以使用如下的形式:
# i和j为循环中某些变量
sql = 'SELECT key1, key2 FROM mydb WHERE vid1=%s AND vid2=%s'%(i, j)
cursor.execute(sql)
# 或者下面这样
sql = 'SELECT key1, key2 FROM mydb WHERE vid1=%s AND vid2=%s'
cursor.execute(sql, (i, j))
第二种方法中,是在执行sql中传入参数来替代sql语句中的占位符"%s"。
写数据库
- 创建表:
同样通过执行sql语句来创建表,比如下面这样:
cursor.execute('DROP TABLE IF EXISTS product_table')
sql = """
CREATE TABLE `product_table` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`cate_id` int(10) NOT NULL DEFAULT '0',
`product_id` int(10) unsigned NOT NULL COMMENT '产品id',
`aid1` int(10) unsigned NOT NULL DEFAULT '0' COMMENT '属性名id一级',
`aid2` int(10) unsigned NOT NULL DEFAULT '0' COMMENT '属性名id二级',
`vid1` int(10) unsigned NOT NULL DEFAULT '0' COMMENT '属性值id一级',
`vid2` int(10) unsigned NOT NULL DEFAULT '0' COMMENT '属性值id二级',
`created_at` datetime NULL DEFAULT NULL,
`updated_at` datetime NULL DEFAULT NULL,
`type` enum('a','b') COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT 'a' COMMENT '类型:a优秀,b一般',
PRIMARY KEY (`id`)
) ENGINE=InnoDB;
"""
print(cursor.execute(sql))
cursor.close()
上面的语句首先判断是否存在product_table表,如果存在,那么将其删除,然后新建一个。如果不删除原来的表,则会无法创建同名的表。这也可以将表命名为不同的名称来实现。创建的表如下:
- 写入单条数据
import time
date = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
content_str = "('1', '102', '100', '200', '10', '30', '%s', '%s', 'a')"%(str(date), str(date))
insert_sql = """INSERT INTO product_table(cate_id, product_id, aid1, aid2, vid1,vid2, created_at, updated_at,type)VALUES""" + content_str
try:
cursor.execute(insert_sql)
# 提交当前的事务
connection.commit()
except Exception as e:
print(e)
# 如果执行不成功,则回滚,类似ctrl-z操作
connection.rollback()
finally:
connection.close()
写入数据时,如果面临着很多的参数需要写入,则可以实现将要插入的数据组合成字符串形式,mysql并不严格限制写入数据的类型,比如你写入了int类型的数据,但是到了表格中,所有都强制转换成str类型,但是我们写的时候,要自己将数据组成字符串形式,避免系统自动转换中出错。写入后如下:
需要注意的是,插入数据库的内容的编写方式,当然还有很多其他的方式,采用这种方式的主要原因是,可以通过对插入内容进行拼接,比如用一个for循环一次拼接1000条,那么在插入的时候,批量插入1000条,效率要高很多。
- 写入批量数据:
insert_list = ''
date = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
# 假设下面的cate_id,product_id等各自都包含1000条内容
for i in range(1000):
content_list = [cate_id[i],product_id[i],aid1[i], aid2[i], vid1[i], vid2[i],date, date,type[i] ]
insert_str = ''
insert_str += '('
for j in content_list:
if j is str:
insert_str += j
else:
insert_str += '\'' + str(j) + '\'' + ','
insert_list += insert_str[:-1] + '),'
insert_sql = """INSERT INTO product_table(cate_id, product_id, aid1, aid2, vid1,vid2, created_at, updated_at,type)VALUES""" + insert_list[:-1]
try:
cursor.execute(insert_sql)
# 提交当前的事务
connection.commit()
except Exception as e:
print(e)
# 如果执行不成功,则回滚,类似ctrl-z操作
connection.rollback()
finally:
connection.close()
上面代码中,最终的insert_list就是要插入的批量数据的内容,可以执行一次插入操作就完成了。