python MySQLdb手动简单操作源码

#!/usr/bin/python

import MySQLdb
from os import system

class myDataBaseConnect(object):

	def insert(self):
		print "Insert Information:"
		info_name	= str(raw_input("name:"))
		info_passwd	= str(raw_input("passwd:"))
		info		= (info_name, info_passwd)
		sql			= "Insert into " + now_table + "(name, pwd) value(%s, %s)"
		cur.execute(sql, info)
		print "Succeedly Insert Information..."
	
	def update(self): 
		print "Update Information:"
		info_name		= str(raw_input("name:"))
		info_new_name	= str(raw_input("new name:"))
		info_passwd	= str(raw_input("new passwd:"))
		info = (info_new_name, info_passwd, info_name)
		sql = "Update " + now_table + " set name=%s, pwd=%s where name=%s"
		cur.execute(sql, info)
		print "Succeedly Update Information..."

	def delete(self):
		print "Update Information:"
		info_name		= str(raw_input("name:"))
		info = (info_name, )
		sql = "Delete from " + now_table + " where name=%s"
		cur.execute(sql, info)
		print "Succeedly Delete Information..."

	def select(self):
		"Go through INfomation:"
		sql = "select * from %s" % now_table
		cur.execute(sql)
		info = cur.fetchall()
		for id, name, passwd in info:
			print "name:%-10s  passwd:%-20s" % (name, passwd)

print "Connect to your Datebase"
now_user	= str(raw_input("username:"))
now_passwd	= str(raw_input("passwd:"))
now_host	= str(raw_input("host:"))
conn = MySQLdb.connect(now_host, now_user, now_passwd)

now_db		= str(raw_input("DataBaseName:"))
conn.select_db(now_db)

print "Welcome to your database %s" % now_db
now_table = str(raw_input("Tables:"))

while True:
	print "1.Insert information"
	print "2.Update information"
	print "3.Delete information"
	print "4.Search information"

	choice = int(raw_input("Your Choice(0 to quit):"))

#	while isinstance(choice, str):
#		choice = raw_input("Error.Please input Correctly!\nYour Choice:")

	#choice = int(choice)
	while choice > 4 or  choice < 0 :
		choice = int(raw_input("Error.Please input Correctly!\nYour Choice:"))
	print "choice : %d " % choice


	cur = conn.cursor()
		
	my_database = myDataBaseConnect()

#choice_option = {
#		1:my_database.insert(),
#		2:my_database.update(),
#		3:my_database.delete(),
#		4:my_database.select(),
#		}

#result = choice_option.get(choice)

#print result
	if choice == 1:
		my_database.insert()
	elif choice == 2:
		my_database.update()
	elif choice == 3:
		my_database.delete()
	elif choice == 4:
		my_database.select()
	else :
		break
	
	conn.commit()
	raw_input("AnyKey to Continue...")

	#clear the screen
	system("clear")

cur.close()
conn.close()

print "Good bye"


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值