from bottle import run,route,static_file,template
import MySQLdb
# 打开数据库连接 url,username,password,database
db = MySQLdb.connect("10.10.10.57","ly","Root123@","pythondb")
#db = MySQLdb.connect("localhost", "testuser", "test123", "TESTDB", charset='utf8' )
# 使用cursor()方法获取操作游标
cursor = db.cursor()
# 使用execute方法执行SQL语句
cursor.execute("SELECT VERSION()")
# 使用 fetchone() 方法获取一条数据
data = cursor.fetchone()
cursor.execute("select name from tp_agent where id = 1")
data1 = cursor.fetchone()
print ("Database version : %s " %data)
print ("tp_agent : %s " %data1)
# 如果数据表已经存在使用 execute() 方法删除表。
#cursor.execute("DROP TABLE IF EXISTS EMPLOYEE")
#创建数据表SQL语句
sql1= """ create table employee (
first_name char(20) not null,
last_name char(20),
age int,
sex char(1),
incom float)"""
#cursor.execute(sql)
#sql 插入语句
sql = """INSERT INTO employee (FIRST_NAME,LAST_NAME, AGE, SEX, INCOM) VALUES('Mac1', 'Mohan1', 20, 'M', 2000)"""
try:
#执行sql语句
print("1111")
cursor.execute(sql)
#提交到数据执行
print("1ok")
db.commit()
except:
# Rollback in case there is any error
print("1fail")
db.rollback()
sqlc = """
create table login (username char(20),pass char(20))
"""
#cursor.execute(sqlc)
user_id = "test"
password = "testpass"
#cursor.execute('insert into login values(%s,%s)' % \
# (user_id,password))
#插入数据,插入数据,插入数据,插入数据,插入数据,插入数据,插入数据,插入数据,
sqli= """ insert into login values('user1','1pass') """
try:
#执行sql语句
print("222")
cursor.execute(sqli)
#提交到数据执行
print("2ok")
db.commit()
except:
# Rollback in case there is any error
print("2fail")
db.rollback()
#打印数据,打印数据,打印数据,打印数据,打印数据,打印数据,打印数据,打印数据,
#SQL查询语句
sqlx= """select * from employee where incom >1000"""
try:
# 执行SQL语句
cursor.execute(sqlx)
# 获取所有记录列表
results = cursor.fetchall()
for row in results:
fname = row[0]
lname = row[1]
age = row[2]
sex = row[3]
income = row[4]
# 打印结果
print ("fname=%s,lname=%s,age=%s,sex=%s,income=%s" % \
(fname, lname, age, sex, income ))
except:
print("Error: unable to fecth data")
# 关闭数据库连接
db.close()