#!/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