下面介绍下如何使用Python对Mysql进行 *** 作,下面是一些简单的例子:使用Python对Mysql数据库进行 *** 作
(1).使用Python连接MySQL:
1 import MySQLdb2 3 try:4 conn = MySQLdb.connect(host="localhost",,user='root',passwd="sina.com",db="mysql",port=3307)5 except MySQLdb.OperationalError,e:6 print "the error msg is :",e
(2).使用Python查询MySQL数据:
1 import MySQLdb 2 3 try: 4 conn=MySQLdb.connect(host='localhost',user='root',passwd='root',db='test',port=3306) 5 cur=conn.cursor() 6 cur.execute('select * from user') 7 cur.close() 8 conn.close() 9 except MySQLdb.Error,e:10 print "Mysql Error %d: %s" % (e.args[0], e.args[1])
(3).使用Python添加和更新MySQL数据:
1 import MySQLdb 2 3 try: 4 conn=MySQLdb.connect(host='localhost',user='root',passwd='root',port=3306) 5 cur=conn.cursor() 6 7 cur.execute('create database if not exists python') 8 conn.select_db('python') 9 cur.execute('create table test(id int,info varchar(20))')10 11 value=[1,'hi rollen']12 cur.execute('insert into test values(%s,%s)',value)13 14 values=[]15 for i in range(20):16 values.append((i,'hi rollen'+str(i)))17 18 cur.executemany('insert into test values(%s,%s)',values)19 20 cur.execute('update test set info="I am rollen" where id=3')21 22 conn.commit()23 cur.close()24 conn.close()25 26 except MySQLdb.Error,e:27 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()
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 '=='*10cur.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])
(4).经常使用的一些API方法:
1 commit() 提交
2 rollback() 回滚
3 cursor用来执行命令的方法:
4 callproc(self, procname, args):用来执行存储过程,接收的参数为存储过程名和参数列表,返回值为受影响的行数
5 execute(self, query, args):执行单条sql语句,接收的参数为sql语句本身和使用的参数列表,返回值为受影响的行数
6 executemany(self, query, args):执行单挑sql语句,但是重复执行参数列表里的参数,返回值为受影响的行数
7 nextset(self):移动到下一个结果集
8 cursor用来接收返回值的方法:
9 fetchall(self):接收全部的返回结果行.
10 fetchmany(self, size=None):接收size条返回结果行.如果size的值大于返回的结果行的数量,则会返回cursor.arraysize条数据.
13 fetchone(self):返回一条结果行.
14 scroll(self, value, mode='relative'):移动指针到某一行.如果mode='relative',则表示从当前所在行移动value条,如果 mode='absolute',则表示从结果集的第一行移动value条。
1、MySQLdb
# 前置条件
sudo apt-get install python-dev libmysqlclient-dev # Ubuntu
sudo yum install python-devel mysql-devel # Red Hat / CentOS
# 安装
pip install MySQL-python
Windows 直接通过下载 exe 文件安装
#!/usr/bin/python
import MySQLdb
db = MySQLdb.connect(
host = "localhost", # 主机名
user = "root", # 用户名
passwd = "pythontab.com", # 密码
db = "testdb") # 数据库名称
# 查询前,必须先获取游标
cur = db.cursor()
# 执行的都是原生SQL语句
cur.execute("SELECT * FROM mytable")
for row in cur.fetchall():
print(row[0])
db.close()
2、mysqlclient
# Windows安装
pip install some-package.whl
# linux 前置条件
sudo apt-get install python3-dev # debian / Ubuntu
sudo yum install python3-devel # Red Hat / CentOS
brew install mysql-connector-c # macOS (Homebrew)
pip install mysqlclient
3、PyMySQL
pip install PyMySQL
# 为了兼容mysqldb,只需要加入
pymysql.install_as_MySQLdb()
import pymysql
conn = pymysql.connect(host = '127.0.0.1', user = 'root', passwd = "pythontab.com", db = 'testdb')
cur = conn.cursor()
cur.execute("SELECT Host,User FROM user")
for r in cur:
print(r)
cur.close()
conn.close()
4、peewee
pip install peewee
import peewee
from peewee import *
db = MySQLDatabase('testdb', user = 'root', passwd = 'pythontab.com')
class Book(peewee.Model):
author = peewee.CharField()
title = peewee.TextField()
class Meta:
database = db
Book.create_table()
book = Book(author = "pythontab", title = 'pythontab is good website')
book.save()
for book in Book.filter(author = "pythontab"):
print(book.title)
5、SQLAlchemy
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from sqlalchemy_declarative import Address, Base, Person
class Address(Base):
__tablename__ = 'address'
id = Column(Integer, primary_key = True)
street_name = Column(String(250))
engine = create_engine('sqlite:///sqlalchemy_example.db')
Base.metadata.bind = engine
DBSession = sessionmaker(bind = engine)
session = DBSession()
# Insert a Person in the person table
new_person = Person(name = 'new person')
session.add(new_person)
session.commit()
1、首要下载装mysql5.msi,“mysql5.msi”,进MySQL装界面,
2、 选择装类,注意下中选择“Custom”(自义)选项,这样才能改装目录。
3、选择装目录:程序默认装系统盘,装选项中选中“MySQL Server”,点“Browse...”改MySQL的装目录。注意不要选择系统盘下的目录,以相数据库为 *** 系统的故障而产生灾难性果(数据文丢),
4、点“浏览”改MySQL装目录为“d:\muse\install\mysql”,
5、MySQL默认数据目录装系统盘,装选项中选中“Server data files”,点“Browse…”改MySQL的数据装目录。注意不要选择系统盘下的目录,以相数据库为 *** 系统的故障而产生灾难性果(数据文丢),
6、改MySQL的数据装目录,数据装目录与mysql一级目录,文称mysqldata,
7、点“Next”,
8、点“Install”开装,
9、下面两步没有特殊选项,直接点“Next”继续装,
10、选择“Detailed Configuration”项,点“Next”,
11、注意,下面要选择“Server Machine”, 点“Next”,
12、选择“Multifunctional Database”,点“Next”继续,
13、InnoDB Tablespace Setting选择Installation Path,点“Next”继续,
14、设置时连接MySQL服的连接数,注意,下面要选择“Manual Setting”项,并选择“Concurrent connections”为“1000”, 点“Next”,
15、设置服端,默认为“3306”, 点“Next”,
16、选择默认符集,下面选择“Manual Selected Default Character Set / Collation”项,并选择默认符集为“utf8”, 点“Next”,
17、装MySQL为Windows *** 系统的服,“Service Name”(服称)项选择“MySQL”,并选“Launch the MySQL Server automatically”( *** 系统时自MySQL服),点“Next”,
18、设置MySQL管理root的码,下面设置为“12345678”为,点“Next”,
19、点“Execute”,开执行配置,
20、点“Finish”成配置,
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)