python 基础 9.7 创建表

一. 创建表
#/usr/bin/python
#-*- coding:utf-8 -*-
#@Time   :2017/11/22 18:05
#@Auther :liuzhenchuan
#@File   :创建表.py
import MySQLdb
 
 
def connect_mysql():
    db_config={
        'host':'192.168.16.70',
        'port':3306,
        'user':'root',
        'passwd':'123123',
        'db':'students',
        'charset':'utf8'
    }
 
    try:
        cnx = MySQLdb.connect (**db_config)
    except Exception as e:
        raise e
    finally:
        return cnx
 
student = '''
    create table student(
        stdid int primary key not null,
        stdname varchar(100) not null,
        gender enum('M','F'),
        agent int
    );
'''
 
course = '''
    create table course(
        couid int primary key not null,
        cname varchar(100) not null,
        tid int not null
    );
'''
 
score = '''
    create table score(
        sid int primary key not null,
        stdid int not null,
        cid int not null,
        grade int not null     
    );
'''
 
teacher = '''
    create table teacher(
        tid int primary key not null,
        tname varchar(100) not null
    );
'''
 
 
tmp = '''
    set @a := 0;
        create table tmp as select (@a := @a + 1) as id from information_schema.tables limit 10;
'''
 
 
if __name__ == '__main__':
    cnx = connect_mysql()
    print cnx
    print dir(cnx)
    cus = cnx.cursor()
    try:
        cus.execute(student)
        cus.execute(course)
        cus.execute(score)
        cus.execute(teacher)
        cus.execute(tmp)
        cus.close()
        cnx.commit()
    except Exception as e:
        raise e
    finally:
        cnx.close()
>>>
<_mysql.connection open to '192.168.16.70' at 32f5078>
['DataError', 'DatabaseError', 'Error', 'IntegrityError', 'InterfaceError', 'InternalError', 'NotSupportedError', 'OperationalError', 'ProgrammingError', 'Warning', '__class__', '__delattr__', '__dict__', '__doc__', '__enter__', '__exit__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', '_server_version', '_transactional', 'affected_rows', 'autocommit', 'begin', 'change_user', 'character_set_name', 'client_flag', 'close', 'commit', 'converter', 'cursor', 'cursorclass', 'default_cursor', 'dump_debug_info', 'encoders', 'errno', 'error', 'errorhandler', 'escape', 'escape_string', 'field_count', 'get_autocommit', 'get_character_set_info', 'get_host_info', 'get_proto_info', 'get_server_info', 'info', 'insert_id', 'kill', 'literal', 'messages', 'next_result', 'open', 'ping', 'port', 'query', 'rollback', 'select_db', 'server_capabilities', 'set_character_set', 'set_server_option', 'set_sql_mode', 'show_warnings', 'shutdown', 'sqlstate', 'stat', 'store_result', 'string_decoder', 'string_literal', 'thread_id', 'unicode_literal', 'use_result', 'warning_count']
 
解释说明:
没有任何异常,在数据库中查看表,出现这五个表。说明这五个表已经创建成功。
既然我们要搞,就尽可能的接近实战,我们来把数据搞大一点,语句设计的复杂一点,这样对我们以后接触到简单的sql语句时,就有很大的帮助。
首先我们先来了解一下information_schema这个库,这个在mysql安装时就有了,提供了访问数据库元数据的方式。那什么是元数据库呢?元数据是关于数据的数据,如数据库名或表名,列的数据类型,或访问权限等。有些时候用于表述该信息的其他术语包括“数据词典”和“系统目录”。
information_schema数据库表说明:
 
SCHEMATA表:提供了当前mysql实例中所有数据库的信息。是show databases的结果取之此表。
 
TABLES表:提供了关于数据库中的表的信息(包括视图)。详细表述了某个表属于哪个schema,表类型,表引擎,创建时间等信息。是show tables from schemaname的结果取之此表。
 
COLUMNS表:提供了表中的列信息。详细表述了某张表的所有列以及每个列的信息。是show columns from schemaname.tablename的结果取之此表。
 
STATISTICS表:提供了关于表索引的信息。是show index from schemaname.tablename的结果取之此表。
 
USER_PRIVILEGES(用户权限)表:给出了关于全程权限的信息。该信息源自mysql.user授权表。是非标准表。
 
SCHEMA_PRIVILEGES(方案权限)表:给出了关于方案(数据库)权限的信息。该信息来自mysql.db授权表。是非标准表。
 
TABLE_PRIVILEGES(表权限)表:给出了关于表权限的信息。该信息源自mysql.tables_priv授权表。是非标准表。
 
COLUMN_PRIVILEGES(列权限)表:给出了关于列权限的信息。该信息源自mysql.columns_priv授权表。是非标准表。
 
CHARACTER_SETS(字符集)表:提供了mysql实例可用字符集的信息。是SHOW CHARACTER SET结果集取之此表。
COLLATIONS表:提供了关于各字符集的对照信息。
 
COLLATION_CHARACTER_SET_APPLICABILITY表:指明了可用于校对的字符集。这些列等效于SHOW COLLATION的前两个显示字段。
 
TABLE_CONSTRAINTS表:描述了存在约束的表。以及表的约束类型。
 
KEY_COLUMN_USAGE表:描述了具有约束的键列。
 
ROUTINES表:提供了关于存储子程序(存储程序和函数)的信息。此时,ROUTINES表不包含自定义函数(UDF)。名为“mysql.proc name”的列指明了对应于INFORMATION_SCHEMA.ROUTINES表的mysql.proc表列。
 
VIEWS表:给出了关于数据库中的视图的信息。需要有show views权限,否则无法查看视图信息。
 
TRIGGERS表:提供了关于触发程序的信息。必须有super权限才能查看该表
 
TABLES在安装好mysql的时候,一定是有数据的,因为在初始化mysql的时候,就需要创建系统表,该表一定有数据。
set @i := 0;
create table tmp as select (@i := @i + 1) as id from information_schema.tables limit 10;
mysql中变量不用事前申明,在用的时候直接用“@变量名”使用就可以了。set这个是mysql中设置变量的特殊用法,当@i需要在select中使用的时候,必须加:,这样就创建好了一个表tmp,查看tmp的数据:
mysql> select * from tmp;
+------+
| id   |
+------+
|    1 |
|    2 |
|    3 |
|    4 |
|    5 |
|    6 |
|    7 |
|    8 |
|    9 |
|   10 |
+------+
10 rows in set (0.00 sec)
我们只是从information_schema.tables表中取10条数据,任何表有10条数据也是可以的,然后把变量@i作为id列的值,分10次不断输出,依据最后select的结果,创建表tmp
 
 
 
posted @ 2017-11-24 04:36  刘振川的博客  阅读(433)  评论(0编辑  收藏  举报