数据库编程实例

判断数据库指定表是否存在

import MySQLdb
db = raw_input('请输入数据库名:')
table_name=raw_input("请输入表名:")
conn =MySQLdb.Connect(user='root',passwd='redhat',host='localhost',db=db,port=3306)
cur=conn.cursor()
cur.execute('show tables;')
for i in cur.fetchall():
    if i[0] == table_name:
        print "%s存在" %table_name
        break
else:
    print "%s不存在" %table_name
conn.commit()
cur.close()
conn.close()

数据库编程实例_第1张图片

数据库封装

数据库编程实例_第2张图片

import time   ###time模块在MySQLdb之前,否则,\__del__方法无法使用
import MySQLdb as mysql


db = {
    'user': 'root',
    'passwd': 'redhat',
    'host': 'localhost',
    'port': 3306,
    'charset': 'utf8',
    'db': 'user',
}


class mMysql(object):
    ##database形式参数
    def __init__(self, **database):
        ##创建数据库的连接
        self.user = database['user']
        self.__passwd = database['passwd']
        self.host = database['host']
        self.__port = database['port']
        self.charset = database['charset']
        self.db = database['db']
        self.conn = mysql.connect(user=self.user, passwd=self.__passwd,
                                  host=self.host, port=self.__port,
                                  db=self.db, charset=self.charset)
        ##创建游标,给数据库发送sql语句
        self.cur = self.conn.cursor()
        print '[%s]:数据库正在链接中...' % time.ctime()

    def is_table_exist(self, table_name):
        self.cur.execute('show tables;')
        for name in self.cur.fetchall():
            if name[0] == table_name:
                return True
        else:
            return False

    def select_table(self, table_name, num=1):
        if self.is_table_exist(table_name):
            self.cur.execute('select * from %s' %table_name)
            for i in self.cur.fetchmany(num):
                print i
        else:
            print '%s不存在' % table_name

    def create_table(self, table_name, **attr):
        s = ''
        if not self.is_table_exist(table_name):
            for k, v in attr.items():
                s = s + k + ' ' + v + ','
            s = s.rstrip(',')
            sqli = 'create table %s(%s);' %(table_name, s)
            print "sqli语句:", sqli
            self.cur.execute(sqli)
            print "%s创建成功" %(table_name)
        else:
            print "%s已经存在了" %(table_name)

    def __del__(self):
        self.cur.close()
        self.conn.close()
        print '[%s]:数据库正在断开...' %(time.time())



sql = mMysql(**db)
sql.create_table('userinfo2', user='varchar(10)', age='int')
# sql.__del__()
# sql.select_table('python',2)
---->>结果
[Tue Apr  3 20:18:29 2018]:数据库正在链接中...
userinfo2已经存在了
[1522757909.76]:数据库正在断开...

数据库编程实例_第3张图片
数据库编程实例_第4张图片
数据库编程实例_第5张图片

应用

数据库编程实例_第6张图片

import random
import string
import MySQLdb as mysql
def cname():
    xing=['许', '张', '赵', '钱', '孙', '李', '朱', '杨']
    ming1=['彬', '群', '宁', '盼', '龙', '欢', '丹']
    ming2 =['彬', '群', '宁', '盼', '龙', '欢', '丹', ' ' ]
    name=random.choice(xing)+random.choice(ming1)+random.choice(ming2)
    return name.rstrip()
def cpd(count=6):
    passwd=(random.sample(string.letters,count-3)+random.sample(string.digits,3))
    return (''.join(passwd))


n=input("num:")
conn=mysql.connect(user='root',passwd='redhat',host='localhost',port=3306,charset='utf8',db='user')
cur=conn.cursor()
cur.execute('create table exam(name varchar(10),passwd varchar(9));')
for i in range(n):
    sqli='insert into exam values("%s","%s");' %(cname(),cpd())
    print sqli
    cur.execute(sqli)
conn.commit()
cur.close()
conn.close()
--->>>
num:10
insert into exam values("赵龙彬","uSy621");
insert into exam values("朱龙群","VfJ035");
insert into exam values("钱丹欢","LuJ631");
insert into exam values("杨宁","FOb657");
insert into exam values("杨龙宁","byA621");
insert into exam values("张彬丹","zuS352");
insert into exam values("李丹龙","lvN251");
insert into exam values("张盼龙","xns357");
insert into exam values("许丹彬","QFd908");
insert into exam values("许欢宁","ZWB748");

数据库编程实例_第7张图片

你可能感兴趣的:(Linux)