MySQLdb的使用

MySQLdb的使用。

1.create table:

 #-*- coding:utf-8 -*-
‘‘‘
    @data:2015-01-05
    @filename:CreateTable.py
‘‘‘
import MySQLdb as mdb
import sys


con = None
try:
    con = mdb.connect(‘localhost‘,‘root‘,‘123456‘,‘py‘)
    cur = con.cursor()
    cur.execute("CREATE TABLE IF NOT EXISTS \
        Writers(Id INT PRIMARY KEY AUTO_INCREMENT,Name VARCHAR(25))")
    cur.execute("INSERT INTO Writers(Name) VALUES(‘Jack London‘)")
    cur.execute("INSERT INTO Writers(Name) VALUES(‘Honore de Balzac‘)")
    cur.execute("INSERT INTO Writers(Name) VALUES(‘Lion‘)")
    cur.execute("INSERT INTO Writers(Name) VALUES(‘Emile‘)")
    cur.execute("INSERT INTO Writers(Name) VALUES(‘Truman Capote‘)")
    print "Database Table Writes Create success."
finally: 
    if con:
        con.close()

2.select table

#-*- coding:utf-8 -*-
‘‘‘
    @data:2015-01-05
    @filename:SelectTable.py
‘‘‘
import MySQLdb as mdb
import sys


con = None
try:
    con = mdb.connect(‘localhost‘,‘root‘,‘123456‘,‘py‘)
    cur = con.cursor()
    cur.execute("SELECT * FROM Writers")
    numrows = int(cur.rowcount)
    for i in range(numrows):
        row = cur.fetchone()
        print row[0],‘|‘,row[1]
finally: 
    if con:
        con.close()

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。