在linux系统上安装并打开数据库并进行安全初始化
安装mysql-python 包
[root@python ~]# yum install MySQL-python.x86_64 -y
mariadb数据库中文编码问题;
环境设定(重启数据库服务后失效):
MariaDB [(none)]> set character_set_database='utf8';
Query OK, 0 rows affected (0.00 sec)
MariaDB [(none)]> set character_set_server ='utf8';
Query OK, 0 rows affected (0.00 sec)
[root@python ~]# vim /etc/my.cnf.d/client.cnf
[root@python ~]# vim /etc/my.cnf.d/server.cnf
数据库的接入:
In [2]: import MySQLdb as mysql ##导入数据库模块
In [4]: conn = mysql.connect(user='root', passwd='westos', db='users', charset='utf8') ##接入数据库(用户,密码,数据库名称,编码格式)
In [5]: cur = conn.cursor() ##创建游标
执行数据库命令:(cur.execute('linux中对数据库命令'))
cur.execute('create table userinfo values(name varchar(20), password varchar(10));') ##创建表
cur.execute('insert into userinfo values("user3", "123");' ##插入表值
cur.execute('select * from userinfo') ##查看表
注意在python里面并不会直接返回数据库内容,要想查看表格信息;
# 1. fetchone() 查看一条信息, 指针向后移动 ;
In [14]: cur.execute('select * from userinfo')
Out[14]: 5L
In [15]: cur.fetchone()
Out[15]: (u'user3', u'123')
In [16]: cur.fetchone()
Out[16]: (u'user1', u'456')
# 2. scroll() 移动指针 ;
cur.scroll(0,'absolute')
# 3. fetchmany(n) 显示多条信息信息
In [18]: cur.fetchmany(3)
Out[18]: ((u'user3', u'123'), (u'user1', u'456'), (u'user2', u'234'))
数据库应用
实例一:
随机生成100个人名和对应的密码;
人名由三个汉字或者2个汉字组成,
姓 = [许, 张, 赵, 钱, 孙, 李, 朱, 杨]
名 = [彬, 群, 宁, 盼, 龙, 欢, 丹]
密码统一6位, 由字母和字符组成;
存储上述用户信息到数据库中, 保存在数据库users中的userinfo表中;
import random import string import MySQLdb as mysql from random import choice as choice def random_user(): user_xing = ["许", "张", "赵", "钱", "孙", "李", "朱", "杨"] user_ming = ["彬", "群", "宁", "盼", "龙", "欢", "丹", "明", "芳"] user_ming2 = ["彬", "群", "宁", "盼", "龙", "欢", "丹", "明", "芳", " "] name = choice(user_xing)+ choice(user_ming) + choice(user_ming2) return name.rstrip() def GenPassword(count=6): nums = random.sample(string.digits,count-3) letters=random.sample(string.letters,3) return "".join(nums + letters) def main(): conn = mysql.connect(user="root", passwd="westos", charset='utf8') cur = conn.cursor() conn.select_db('user') nu = input("请输入想要生成的个数:") for i in range(nu): sqli = 'insert into userinfo values ("%s","%s");' %(random_user(),GenPassword()) cur.execute(sqli) conn.commit() cur.close() conn.close() main()
实例二:
应用之封装MySQLdb编写create_table(self, table_name, **attr )方法, 实现创建表, 创建前判断表是否存在, **attr是表的属性名;
import MySQLdb as mysql DB_CONFIG={ ##定义一个字典存储登陆数据库的信息 'name':'root', 'passwd':'westos', 'db':'user', 'port':3306, 'host':'localhost', 'charset' : 'utf8', } class MyMySQL(object): ##封装一个数据库类 def __init__(self,**db_config): self.name = db_config['name'] self.__passwd=db_config['passwd'] self.db=db_config['db'] self.host=db_config['host'] self.port=db_config['port'] self.charset=db_config['charset'] self.conn=mysql.connect( ##连接数据库 user=self.name, passwd=self.__passwd, db=self.db, host=self.host, port=self.port, charset=self.charset ) self.cur = self.conn.cursor() print "Connection is successful!!" def isTableExit(self,table_name,db_name=None): ##判断表是否存在 if db_name != None: self.conn.select_db(db_name) ##如果传入参数中有数据库名db_name,则选择新的数据库 self.cur.execute('show tables;') for i in self.cur.fetchall(): if i[0] == table_name: return True else: return False def select_table(self, table_name, num=None): ##选择查看表里面的内容 if self.isTableExit(table_name): self.cur.execute('select * from %s;' %table_name) if num == None: return self.cur.fetchall() ##如果传入参数中没有数字,则显示所有数据,否则显示传入数字的对应行数 else: return self.cur.fetchmany(num) else: return "%s 不存在" %(table_name) def create_table(self,table_name,**attr): ##创建表 if self.isTableExit(table_name): return "%s 已经存在" %(table_name) else: s = '' for key,value in attr.items(): s = s + key + " " + value + "," s = s.rstrip(",") sqli = 'create table %s (%s);' %(table_name,s) self.cur.execute(sqli) return "%s 创建成功" %(table_name) def __del__(self): self.conn.commit() self.cur.close() self.conn.close() print "Connection is broken down!!" a = MyMySQL(**DB_CONFIG) print a.db print a.isTableExit('userinfo') print a.select_table('base') print a.create_table('userinfo',username ='varchar(10)',passwd ='varchar(10)' )