
import MySQLdb
try:
conn=MySQLdb.connect(host='localhost',user='root',passwd='root',db='test',port=3306)
cur=conn.cursor()
cur.execute('select * from user')
cur.close()
conn.close()
except MySQLdb.Error,e:
print "Mysql Error %d: %s" % (e.args[0], e.args[1])
请注意修改你的数据库,主机名,用户名,密码。
下面来大致演示一下插入数据,批量插入数据,更新数据的例子吧:
import MySQLdb
try:
conn=MySQLdb.connect(host='localhost',user='root',passwd='root',port=3306)
cur=conn.cursor()
cur.execute('create database if not exists python')
conn.select_db('python')
cur.execute('create table test(id int,info varchar(20))')
value=[1,'hi rollen']
cur.execute('insert into test values(%s,%s)',value)
values=[]
for i in range(20):
values.append((i,'hi rollen'+str(i)))
cur.executemany('insert into test values(%s,%s)',values)
cur.execute('update test set info="I am rollen" where id=3')
conn.commit()
cur.close()
conn.close()
except MySQLdb.Error,e:
print "Mysql Error %d: %s" % (e.args[0], e.args[1])
请注意一定要有conn.commit()这句来提交事务,要不然不能真正的插入数据。
运行之后我的MySQL数据库的结果就不上图了。
import MySQLdb
try:
conn=MySQLdb.connect(host='localhost',user='root',passwd='root',port=3306)
cur=conn.cursor()
conn.select_db('python')
count=cur.execute('select * from test')
print 'there has %s rows record' % count
result=cur.fetchone()
print result
print 'ID: %s info %s' % result
results=cur.fetchmany(5)
for r in results:
print r
print '=='*10
cur.scroll(0,mode='absolute')
results=cur.fetchall()
for r in results:
print r[1]
conn.commit()
cur.close()
conn.close()
except MySQLdb.Error,e:
print "Mysql Error %d: %s" % (e.args[0], e.args[1])
运行结果就不贴了,太长了。
查询后中文会正确显示,但在数据库中却是乱码的。经过我从网上查找,发现用一个属性有可搞定:
在Python代码
conn = MySQLdb.Connect(host='localhost', user='root', passwd='root', db='python') 中加一个属性:
改为:
conn = MySQLdb.Connect(host='localhost', user='root', passwd='root', db='python',charset='utf8')
charset是要跟你数据库的编码一样,如果是数据库是gb2312 ,则写charset='gb2312'。
下面贴一下常用的函数:
然后,这个连接对象也提供了对事务 *** 作的支持,标准的方法
commit() 提交
rollback() 回滚
cursor用来执行命令的方法:
callproc(self, procname, args):用来执行存储过程,接收的参数为存储过程名和参数列表,返回值为受影响的行数
execute(self, query, args):执行单条sql语句,接收的参数为sql语句本身和使用的参数列表,返回值为受影响的行数
executemany(self, query, args):执行单挑sql语句,但是重复执行参数列表里的参数,返回值为受影响的行数
nextset(self):移动到下一个结果集
cursor用来接收返回值的方法:
fetchall(self):接收全部的返回结果行.
fetchmany(self, size=None):接收size条返回结果行.如果size的值大于返回的结果行的数量,则会返回cursor.arraysize条数据.
fetchone(self):返回一条结果行.
scroll(self, value, mode='relative'):移动指针到某一行.如果mode='relative',则表示从当前所在行移动value条,如果 mode='absolute',则表示从结果集的第一行移动value条.
参考资料:
MySQLdb‘s user guide
package MySQLdb
pymysql 基本使用 八个步骤以及案例分析一.导入pymysql模块
导入pymysql之前需要先安装pymysql模块
方法一:直接在pycharm编译器里面输入 pip install pymysql
方法二:win+r -->输入cmd -->在里面输入pip install pymysql
ps:在cmd中输入pip list后回车 可以找到安装的pymysql就表示安装成功了
1
2
3
4
5
6
1
2
3
4
5
6
在pycharm编译器中导入
import pymysql
1
2
1
2
二.获取到database的链接对象
coon = pymysql.connect(host='127.0.0.1', user='root', password='123456', database='pymysql_test')
1
1
user:是你的数据库用户名
password:数据库密码
database:你已经创建好的数据库
1
2
3
1
2
3
三.创建数据表的方法
cursor.execute(
'''create table if not exists pets(id int primary key auto_increment,
src varchar(50),
skill varchar(100)''')
1
2
3
4
1
2
3
4
四.获取执行sql语句的光标对象
cousor = coon.cousor()
1
1
五.定义要执行的sql语句
1.sql的增加数据的方法
sql = '''insert into test_mysql(id,src,skill) values(%d,%s,%s)'''
1
1
ps: test_mysql 是你连接到的数据库中的一张表
id,src,skill 这个是你创建表时所定义的字段关键字
%d,%s,%s 这个要根据你创建的字段关键字的类型而定,记住要一一对应
1
2
3
1
2
3
2.sql的删除数据的方法
sql_1 = '''delete from test_mysql where src=%s'''
1
1
3.sql的修改数据方法
sql_2 = '''update test_mysql set src=%s where skill=%s'
1
1
4.sql的查询方法
sql_3 = '''select * from test_mysql where skill = %s'''
1
1
六.通过光标对象执行sql语句
1.执行增加数据的sql语句
cousor.execute(sql, [2, 'www.sohu.com', '000000'])
运行后在mysql的可视化后台就可以直观的添加的数据
1
2
1
2
2.执行删除数据sql语句
new = 'www.baidu.com'
cousor.execute(sql_1, [new])
PS:这里就是根据sql语句where后面的条件进行删除对应的数据
要记住传入的数据要与sql的where后面条件匹配
1
2
3
4
1
2
3
4
3.执行修改数据的sql语句
url = 'www.baidu.com'
pwd = '666666'
cousor.execute(sql_2,[pwd,url])
1
2
3
1
2
3
4.执行查询数据的sql语句
result1 = cousor.fetchone()
fetchone() 查询=整个表中的第一条数据,
如果再次使用就会查找到第二条数据,
还可以在括号内输入id值查询到相应的数据
result2 = cousor.fetchmany()
fetchmany()查询到表里的多条数据,
在括号里输入几就会查找到表的前几条数据
result2 = cousor.fetchall()
fetchall()查询到sql查询匹配到的所有数据
print(result)
用print输出语句就能直接打印输出所查询到的数据
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
**总结: 在执行sql语句要传入参数时,这个参数要以列表或者元组的类型传入**
1
1
七.关闭光标对象
cousor.close()
1
1
八.关闭数据库的链接对象
coon.cousor()
1
1
九.洛克王国宠物数据抓取案例
import requests
import pymysql
from lxml import etree
from time import sleep
# 数据库链接
conn = pymysql.connect(host='127.0.0.1', user='root', password='123456', database='pymysql')
cursor = conn.cursor()
# 执行一条创建表的 *** 作
cursor.execute(
'''create table if not exists pets(id int primary key auto_increment,name varchar(50),src varchar(100),industry text)''')
url = 'http://news.4399.com/luoke/luokechongwu/'
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0Win64x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/101.0.0.0 Safari/537.36'
}
response = requests.get(url=url, headers=headers)
response.encoding = 'gbk'
html = response.text
# print(html)
# 宠物名称
# 宠物图片(图片在 lz_src)
# 宠物技能(跳转详细页)
tree = etree.HTML(html)
li_list = tree.xpath('//ul[@id="cwdz_list"]/li') # 所有的宠物
for li in li_list:
name = li.xpath('./@name')[0] # 每一个宠物的名称
src = 'http:' + li.xpath('./a/img/@lz_src')[0] # 图片链接
link = 'http://news.4399.com' + li.xpath('./a/@href')[0] # 宠物的详细链接
industry = [] # 数组里面存放每一个对象,每一个对象就是一个技能
# 对详细链接发起请求,获取技能
try:
detail_resp = requests.get(url=link, headers=headers)
sleep(0.5)
detail_resp.encoding = 'gbk'
detail_tree = etree.HTML(detail_resp.text)
# 技能
skills = detail_tree.xpath('/html/body/div[5]/div[2]/div[2]/div[1]/div[1]/table[4]/tbody/tr')
del skills[0]
del skills[0]
for skill in skills:
item = {}
item['name'] = skill.xpath('./td[1]/text()')[0] # 技能
item['grade'] = skill.xpath('./td[2]/text()')[0] # 等级
item['property'] = skill.xpath('./td[3]/text()')[0] # 属性
item['type'] = skill.xpath('./td[4]/text()')[0] # 类型
item['target'] = skill.xpath('./td[5]/text()')[0] # 目标
item['power'] = skill.xpath('./td[6]/text()')[0] # 威力
item['pp'] = skill.xpath('./td[7]/text()')[0] # pp
item['result'] = skill.xpath('./td[8]/text()')[0] # 效果
industry.append(item)
# print(industry)
# 数据保存 (mysql)
sql = '''insert into pets(name,src,industry) values (%s,%s,%s)'''
cursor.execute(sql, [name, src, str(industry)])
conn.commit()
print(f'{name}--保存成功!')
except Exception as e:
pass
cursor.close()
conn.close()
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
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
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
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
十.总结
本章内容主要是给大家讲解一下在爬虫过程中如何将数据保存mysql数据库中去,
最后面这个案例就是一个示范,希望这篇文章能给大家带来帮助,都看到这里了给
个三连支持一下吧!!!
1
2
3
1
2
3
float本身保存的就是近似值,因为你后面有e-06这样的字符,这个其实也是数字的一部分,这么看,不管你怎么存小数位都是不够的,比如这个3.90104e-06,翻译过来应该是0.00000390194,你估计float的话要怎么写,他是8位的精度,这里来看最好就是0.0000039也就这样了,我想就算这个也不是你要的吧。所以个人觉得办法就是换一个数据类型,最简单的就是double(我估计16位的精度应该够了吧,不过他和float一样,存一个近似值,你可以试试写成double(16,14)试试,如果还不行,那就只能用decimal了),如果还是进位,那就用decimal(65位的定点数,怎么算都够了。)
如果还不行就祭出终极大招字符型,这个总没有问题,当然如果你还要计算,那就最好别用这个。
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)