1、在進(jìn)行連接之前我們要確定我們已經(jīng)安裝了python和mysql(開(kāi)玩笑恬叹,沒(méi)有這個(gè)你怎么連接那)至于安裝的過(guò)程在此略過(guò)搀别,
2、因?yàn)橐M(jìn)行連接mysqldb 所有我們要導(dǎo)入MySQLdb的模塊砌滞,當(dāng)然這個(gè)模塊在默認(rèn)的python中是沒(méi)有的,https://pypi.python.org/pypi/MySQL-python/1.2.5我們可以在這里進(jìn)行下載坏怪,安裝贝润;
3、代碼
import MySQLdb (導(dǎo)入MySQLdb 模塊)
conn = MySQLdb.connect( host='localhost',user='root',passwd='')
conn.select_db('test')(選擇數(shù)據(jù)庫(kù))
以上是連接數(shù)據(jù)庫(kù)的代碼 切記注意MySQLdb 的大小寫(xiě)的區(qū)分 铝宵,否則會(huì)報(bào)錯(cuò):ImportError: No module named MYSQLdb
增加;
sql='''insert into user (name) values(1)'''
try:
cursor.execute(sql)
conn.commit()
except :
conn.rollback()
conn.close();
刪除:
sql='''delete from user where id =1'''
try:
cursor.execute(sql)
conn.commit()
except Exception, e:
conn.rollback();
print cursor.execute(sql)
else:
print cursor.execute(sql)
finally:
conn.close()
修改:
sql = "update user set name='zhy' where id=2"
cursor.execute(sql)
conn.commit()
查詢:
result=cursor.execute('''select * from user''')
# print result
row = cursor.fetchall()
for r in row:
print r[1](這里是每個(gè)字段的號(hào))