Python Mysql 交互
A、Alex 的语法展示:
import MySQLdb try: conn=MySQL.connect(host=’localhost’,user=’root’,passwod=’123qwe’,db=’test-DB’,port=’3306′) cur =conn.cursor() cur.execute(‘select * from user_info’) cur.close() conn.close()except MySQLdb.Errot,e: print ‘Mysql Error Msg:’ , e B、例子:例子1、获取数据
# 打开数据库连接
db = MySQLdb.connect("localhost","root","123qwe","host_list" )
# 使用cursor()方法获取操作游标
cursor = db.cursor()
# 使用execute方法执行SQL语句
cursor.execute("SELECT VERSION()")
# 使用 fetchone() 方法获取一条数据库。【以-行计数】
data = cursor.fetchone()
print "Database version : %s " % data
# 关闭数据库连接
db.close()
2、插去数据;
# 创建数据表SQL语句
sql = """CREATE TABLE EMPLOYEE (
FIRST_NAME CHAR(20) NOT NULL,
LAST_NAME CHAR(20),
AGE INT,
SEX CHAR(1),
INCOME FLOAT )"""try:
# 执行sql语句
cursor.execute(sql)
# 提交到数据库执行
db.commit()
except:
# Rollback in case there is any error
db.rollback()
常用函数:注意这个 commit( ) 提交 rollback( ) 回滚
(二)、插去多条数据。
#!/usr/bin/python
#coding:utf-8
try:
import MySQLdb
db = MySQLdb.connect("localhost","root","123qwe","host_list" )
cursor = db.cursor()
v_list = []
for i in range(10):
v_list.append(("linux%s" %i,"moban%s" %i,"12%s" %i,"M", "2000"))
print v_list
cursor.executemany( "INSERT INTO EMPLOYEE \
VALUES (%s, %s, %s, %s, %s)", v_list)
cursor.close()
db.commit()
db.close()
except MySQLdb.Error,e:
print 'Mysql Error Msg:',e
例子展示:
释义: cur.scroll(3,mode=”relative”) # 光标相对的移动到 第三行; cur.scroll(0,mode=’absolute’) print cur.fetchone ( ) # 取一行内容;从当前游标处。 print cur.fetchall( ) #从当前位置取全部的行; ps: 默认的 是从 0行开始的,
执行结果后: