python-db 数据库操作test

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()
    
 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值