python脚本之与mysql交互
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python脚本之与mysql交互相关的知识,希望对你有一定的参考价值。
yum install mysql-server
service mysqld start
[[email protected] ~]# mysql -u root
mysql> SET PASSWORD FOR ‘root‘@‘localhost‘ = PASSWORD(‘123456‘);
mysql> show databases;
mysql> use mysql;
mysql> show databases;
mysql>quit
yum install MySQL-python
#######################################################
#!/usr/bin/env python
#encoding=utf-8
import MySQLdb
try:
conn=MySQLdb.connect(host=‘localhost‘,user=‘root‘,passwd=‘123456‘,db=‘mysql‘,port=3306)
cur=conn.cursor()
cur.execute(‘select * from mysql.user‘)
#result=cur.fetchmany(2)
#result=cur.fetchone()
result=cur.fetchall()
for line in result:
print line,
cur.close()
conn.close()
except MySQLdb.Error,e:
print ‘Mysql error Msg:‘,e
#######################################################往数据库批量添加数据
#!/usr/bin/env python
#encoding=utf-8
import MySQLdb
try:
conn=MySQLdb.connect(host=‘localhost‘,user=‘root‘,passwd=‘123456‘,port=3306)
cur=conn.cursor()
try:
cur.execute(‘create database python;‘)
except:
pass
conn.select_db(‘python‘)
try:
cur.execute(‘create table host(id INT NOT NULL AUTO_INCREMENT,primary key(id),host varchar(20),user varchar(20));‘)
except:
pass
values=[]
print ‘aa‘
for i in range(20):
ip=‘192.168.1.%s‘%i
user=‘USER%s‘%i
values.append((‘‘,ip,user))
cur.executemany(‘insert into host values(%s,%s,%s)‘,values)
conn.commit()
cur.close()
conn.close()
except MySQLdb.Error,e:
print ‘Mysql error Msg:‘,e
##############################################################
本文出自 “银河系|计算机网络” 博客,请务必保留此出处http://qqran.blog.51cto.com/10014850/1962307
以上是关于python脚本之与mysql交互的主要内容,如果未能解决你的问题,请参考以下文章