python连接mysql

#!/usr/bin/python
#connect.py - connect to mysql server

import sys
import MySQLdb

try:
        conn = MySQLdb.connect (db = "databasename",
	                           host = "ip address",
                               user = "username",
                               passwd = "pwd")
        print "Connected"
except:
        print "Cannot connect to DB server"
        sys.exit(1)

conn.close()
print "Disconnected"

测试连接的小程序。

是从《mysql cookbook》一个章节中截取出来的。

接着,从mysql里查询等操作,可以用下面的语句实现:

cursor = conn.cursor()
sql = "select a,b,c from my_tb where isreal=0"
cursor.execute(sql)
alldata = cursor.fetchall()

if alldata:
	for rec in alldata:
		print(rec)

带变量的查询:

c=db.cursor()
max_price=5
c.execute("""SELECT spam, eggs, sausage FROM breakfast
          WHERE price < %s""", (max_price,))

c.executemany(
      """INSERT INTO breakfast (name, spam, eggs, sausage, price)
      VALUES (%s, %s, %s, %s, %s)""",
      [
      ("Spam and Sausage Lover's Plate", 5, 1, 8, 7.95 ),
      ("Not So Much Spam Plate", 3, 2, 0, 3.95 ),
      ("Don't Wany ANY SPAM! Plate", 0, 4, 3, 5.95 )
      ] 

 


If you have any questions or ideas ,please feel free to contact me : )

thx.^^


QQ: 1623213673



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值