2017-11-03python3操作mysql数据库

来源:互联网 发布:手机黄金看盘软件 编辑:程序博客网 时间:2024/05/18 09:11
#引入数据库模块
import pymysql

#连接 数据库
db = pymysql.connect('localhost', 'root', '123456', 'testDB')
# 使用cursor()方法创建一个游标对象
cursor = db.cursor()

# 使用execute()方法执行sql查询
# 返回数据库中的总行数
SQL = "select * from cus;"

# cursor.execute()执行数据库命令 返回行数
a = cursor.execute(SQL)
print(a)

# 使用方法fetchone()读取一行,返回数据库中的一行元组
data = cursor.fetchone()
print('第一行:', data)

# 创建一个表格cus 备份create table
if not exists数据库中有这个表则不创建,否则创建一个新表格

s1 = 'create table if not exists cus11(\
id int,\
name VARCHAR(20),\
age int,\
address char(25),\
salary decimal(18,2),\
gender varchar(20));'

# cursor.execute()执行数据库命令
cursor.execute(s1)

#将数据库cus中的数据拷贝到cus11中
#方法:insert  into  表2(column1...) select column1,........ from cus; 
# 复制一次下次再次执行应注释掉次代码,会发生重复错误
####################################################
s2 = 'insert into cus11 (id,name,age,address,salary,gender) \
select id,name,age,address,salary,gender from cus;'
###################################################
# cursor.execute()执行数据库命令
cursor.execute(s2)
cursor.execute('select * from cus11;')


# rowcount是一个只读属性返回执行execute(SQL1)行数
print(cursor.rowcount)

# 返回数据库中表格的元组
sss = cursor.fetchall()
# cursor.rowcount  返回的考入多少行

print(sss)
for row in sss:
    id1 = row[0]
    name1 = row[1]
    age1 = row[2]
    address1 = row[3]
    salary1 = row[4]
    gender1 = row[5]
    print(str(id1), str(name1), str(age1), str(
        address1), str(salary1), str(gender1))

# 将执行的语句送到数据库
db.commit()
# 关闭链接
db.close()
#######################################################
以下完整代码,已经测试

import pymysql

db = pymysql.connect('localhost', 'root', '123456', 'testDB')
cursor = db.cursor()

SQL = "select * from cus;"

a = cursor.execute(SQL)
print(a)

data = cursor.fetchone()
print('第一行:', data)

s1 = 'create table if not exists cus11(\
id int,\
name VARCHAR(20),\
age int,\
address char(25),\
salary decimal(18,2),\
gender varchar(20));'

cursor.execute(s1)

s2 = 'insert into cus11 (id,name,age,address,salary,gender) \
select id,name,age,address,salary,gender from cus;'

cursor.execute(s2)
cursor.execute('select * from cus11;')

print(cursor.rowcount)

sss = cursor.fetchall()

print(sss)
for row in sss:
    id1 = row[0]
    name1 = row[1]
    age1 = row[2]
    address1 = row[3]
    salary1 = row[4]
    gender1 = row[5]
    print(str(id1), str(name1), str(age1), str(
        address1), str(salary1), str(gender1))

# 将执行的语句送到数据库
db.commit()
# 关闭链接
db.close()a

原创粉丝点击