搜索
首页数据库mysql教程MySQLSchema设计(五)用Python管理字符集_MySQL

pythonbitsCN.com 一提字符集,可能有人会说,不管天崩地裂,全用utf8,整个世界都清净了。但某些字符集是需要更多CPU、消费更多的内存和磁盘空间、甚至影响索引使用,这还不包括令人蛋碎的乱码。可见、我们还是有必要花点时间略懂下MySQL字符集。
# 囊括三个层级:

DB、Table、Column mysql> create database d charset utf8; Query OK, 1 row affected (0.04 sec) 
mysql> create table d.t -> (str varchar(10) charset latin1) -> 
default charset=utf8; Query OK, 0 rows affected (0.05 sec)
㈠ 显示字符集
mysql> desc sakila.actor;
 +-------------+----------------------+------+-----+-------------------+-----------------------------+ 
 | Field | Type | Null | Key | Default | Extra | 
 +-------------+----------------------+------+-----+-------------------+-----------------------------+ 
 | actor_id | smallint(5) unsigned | NO | PRI | NULL | auto_increment | 
 | first_name | varchar(45) | NO | | NULL | 
 | | last_name | varchar(45) | NO | MUL | NULL | 
 | | last_update | timestamp | NO | | CURRENT_TIMESTAMP | on update CURRENT_TIMESTAMP |
  +-------------+----------------------+------+-----+-------------------+-----------------------------+ 
  4 rows in set (0.00 sec)
[root@DataHacker ~]
# cat dbapi.py 
#!/usr/bin/env ipython 
#coding = utf-8 
#Author: linwaterbin@gmail.com 
#Time: 2014-1-29 import MySQLdb as dbapi 
USER = 'root' PASSWD = 'oracle' HOST = '127.0.0.1' DB = 'sakila' 
conn = dbapi.connect(user=USER,passwd=PASSWD,host=HOST,db=DB)
[root@DataHacker ~]
# ./show_charset.py --version 1.0
[root@DataHacker ~]# ./show_charset.py -h Usage: show_charset.py [options] 
<arg1> 
<arg2> 
[<arg3>...] Options: --version show program&#39;s version number and exit -h, --help show this help message 
and exit -d DB_NAME Database name(leave blank is all Databases) -t T_NAME Table name 
(leave blank is all tabless) -c C_NAME Column name(leave blank is all columns)
[root@DataHacker ~]
# ./show_charset.py -d sakila -t actor sakila.actor.first_name: 
utf8 utf8_general_ci sakila.actor.last_name: utf8 utf8_general_ci
mysql> create table tt (str char(2) charset utf8); 
Query OK, 0 rows affected (0.20 sec) mysql> create table tt (str int(11) charset utf8); 
ERROR 1064 (42000): You have an error in your SQL syntax; 
check the manual that corresponds to your 
MySQL server version for the right syntax to use near &#39;charset utf8)&#39; at line 1
[root@DataHacker ~]# cat show_charset.py #!/usr/bin/env python from optparse import OptionParser from 
dbapi import conn import MySQLdb 
# 函数一:命令行参数输入 def parse_options(): parser = OptionParser(usage="%prog [options] 
<arg1> <arg2> [<arg3>...]",version=&#39;1.0&#39;,) 
parser.add_option("-d",dest="db_name",help="Database name(leave blank is all Databases)") 
parser.add_option("-t",dest="t_name",help="Table name (leave blank is all tabless)") 
parser.add_option("-c",dest="c_name",help="Column name(leave blank is all columns)") return 
parser.parse_args() # 主功能实现:显示字符集 def show_charsets(): query="""
select * from information_schema.columns where table_schema not in (&#39;mysql&#39;,&#39;INFORMATION_SCHEMA&#39;) 
and character_set_name is not null""" 
#三个if条件实现过滤 if options.db_name: query += " and table_schema=&#39;%s&#39;" % 
options.db_name if options.t_name: query += " and table_name=&#39;%s&#39;" % 
options.t_name if options.c_name: query += " and column_name=&#39;%s&#39;" % options.c_name 
#默认返回值形式是元组,我们通过属性cursors.DictCursor转为字典 
cur = conn.cursor(MySQLdb.cursors.DictCursor) 
cur.execute(query) for record in cur.fetchall(): 
character_set_name = record[&#39;CHARACTER_SET_NAME&#39;] 
collation_name = record[&#39;COLLATION_NAME&#39;] 
print "%s.%s.%s:t%st%s" % (record[&#39;TABLE_SCHEMA&#39;],
record[&#39;TABLE_NAME&#39;],record[&#39;COLUMN_NAME&#39;],character_set_name,collation_name) 
cur.close() #采用try-finally形式关闭数据库连接 
try: options,args = parse_options() show_charsets() finally: conn.close()

㈡ 修改列的字符集

[root@DataHacker ~]# ./modify.py -h Usage: modify.py schema_name.table_name.column_name 
new_charset_name [new_collate_name] Options: --version show program&#39;s version number 
and exit -h, --help show this help message and exit
#修改前 mysql> show create table testdb.tG; 
*************************** 1. row *************************** 
Table: t Create 
Table: CREATE TABLE `t` ( `id` int(11) DEFAULT NULL, 
`name` varchar(10) CHARACTER SET latin1 DEFAULT NULL ) 
ENGINE=InnoDB DEFAULT CHARSET=utf8 1 row in set (0.00 sec) 
#修改 [root@DataHacker ~]# ./modify.py testdb.t.name gbk successfully executed: alter table testdb.t 
modify column name varchar(10) CHARSET gbk #修改后 mysql> show create table testdb.tG; 
*************************** 1. row *************************** 
Table: t Create 
Table: CREATE TABLE `t` ( `id` int(11) DEFAULT NULL, 
`name` varchar(10) CHARACTER SET gbk DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8 1 row in set (0.01 sec)
[root@DataHacker ~]# cat modify.py #!/usr/bin/env python import MySQLdb from dbapi import * from optparse 
import OptionParser 
#这里省略掉option值,只要求输入args def parse_options(): 
parser = OptionParser(usage="n%prog schema_name.table_name.column_name new_charset_name [new_collate_name]",
version=&#39;1.0&#39;,) return parser.parse_args() 
#主程序 def modify_column(): cur = conn.cursor(MySQLdb.cursors.DictCursor) v_sql = """
 select * from information_schema.columns where table_schema=&#39;%s&#39; and table_name=&#39;%s&#39; 
 and column_name=&#39;%s&#39;""" % (schema_name,table_name,column_name) cur.execute(v_sql) row = cur.fetchone() 
 #当row为null时,程序请求检查column是否存在 if not row: print "
 please check schema_name.table_name.column_name whether exists ?" exit(1) column_type = row[&#39;COLUMN_TYPE&#39;] 
 column_default = row[&#39;COLUMN_DEFAULT&#39;] is_nullable = (row[&#39;IS_NULLABLE&#39;] == &#39;YES&#39;) 
 query = "alter table %s.%s modify column %s %s" % (schema_name,table_name,column_name,column_type) 
 query += " CHARSET %s" % new_charset if collation_supplied: 
 query += "COLLATE %s" % new_collation if not is_nullable: query += "NOT NULL" if column_default: 
 query += "DEFAULT &#39;%s&#39;" % column_default try: alter_cur = conn.cursor() alter_cur.execute(query) 
 print "successfully executed:n t%s" % query finally: alter_cur.close() cur.close() 
 try: (options,args) = parse_options() 
 if not 2<= len(args) <=3: print "Usage: schema_name.table_name.column_name 
 new_charset_name [new_collate_name]" exit(1)
  column_tokens = args[0].split(".") if len(column_tokens) != 3: 
  print "column must in the following format: schema_name.table_name.column_name" exit(1) 
  schema_name,table_name,column_name = column_tokens 
  new_charset = args[1] collation_supplied = (len(args) == 3) 
  if collation_supplied: new_collation = args[2] 
  modify_column() finally: 
  if conn: conn.close()

以上就是MySQLSchema设计(五)用Python管理字符集_MySQL的内容,更多相关内容请关注PHP中文网(www.php.cn)!


声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
如何在MySQL中删除或修改现有视图?如何在MySQL中删除或修改现有视图?May 16, 2025 am 12:11 AM

todropaviewInmySQL,使用“ dropviewifexistsview_name;” andTomodifyAview,使用“ createOrreplaceViewViewViewview_nameAsSelect ...”。whendroppingaview,asew dectivectenciesanduse和showcreateateviewViewview_name;“ tounderStanditSsstructure.whenModifying

MySQL视图:我可以使用哪些设计模式?MySQL视图:我可以使用哪些设计模式?May 16, 2025 am 12:10 AM

mySqlViewScaneFectectialized unizedesignpatternslikeadapter,Decorator,Factory,andObserver.1)adapterPatternadaptSdataForomDifferentTablesIntoAunifiendView.2)decoratorPatternenhancateDataWithCalcalcualdCalcalculenfields.3)fieldfields.3)

在MySQL中使用视图的优点是什么?在MySQL中使用视图的优点是什么?May 16, 2025 am 12:09 AM

查看InMysqlareBeneForsImplifyingComplexqueries,增强安全性,确保dataConsistency,andOptimizingPerformance.1)他们simimplifycomplexqueriesbleiesbyEncapsbyEnculatingThemintoreusableviews.2)viewsEnenenhancesecuritybyControllityByControllingDataAcces.3)

如何在MySQL中创建一个简单的视图?如何在MySQL中创建一个简单的视图?May 16, 2025 am 12:08 AM

toCreateAsimpleViewInmySQL,USEthecReateaTeviewStatement.1)defitEtheetEtheTeViewWithCreatEaTeviewView_nameas.2)指定usethectstatementTorivedesireddata.3)usethectStatementTorivedesireddata.3)usetheviewlikeatlikeatlikeatlikeatlikeatlikeatable.views.viewssimplplifefifydataaccessandenenanceberity but consisterfort,butconserfort,consoncontorfinft

MySQL创建用户语句:示例和常见错误MySQL创建用户语句:示例和常见错误May 16, 2025 am 12:04 AM

1)foralocaluser:createUser'localuser'@'@'localhost'Indidendify'securepassword'; 2)foraremoteuser:creationuser's creationuser'Remoteer'Remoteer'Remoteer'Remoteer'Remoteer'Remoteer'Remoteer'Remoteer'Rocaluser'@'localhost'Indidendify'seceledify'Securepassword'; 2)

在MySQL中使用视图的局限性是什么?在MySQL中使用视图的局限性是什么?May 14, 2025 am 12:10 AM

mysqlviewshavelimitations:1)他们不使用Supportallsqloperations,限制DatamanipulationThroughViewSwithJoinSorsubqueries.2)他们canimpactperformance,尤其是withcomplexcomplexclexeriesorlargedatasets.3)

确保您的MySQL数据库:添加用户并授予特权确保您的MySQL数据库:添加用户并授予特权May 14, 2025 am 12:09 AM

porthusermanagementInmysqliscialforenhancingsEcurityAndsingsmenting效率databaseoperation.1)usecReateusertoAddusers,指定connectionsourcewith@'localhost'or@'%'。

哪些因素会影响我可以在MySQL中使用的触发器数量?哪些因素会影响我可以在MySQL中使用的触发器数量?May 14, 2025 am 12:08 AM

mysqldoes notimposeahardlimitontriggers,butacticalfactorsdeterminetheireffactective:1)serverConfiguration impactactStriggerGermanagement; 2)复杂的TriggerSincreaseSySystemsystem load; 3)largertablesslowtriggerperfermance; 4)highConconcConcrencerCancancancancanceTigrignecentign; 5); 5)

See all articles

热AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover

AI Clothes Remover

用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Clothoff.io

Clothoff.io

AI脱衣机

Video Face Swap

Video Face Swap

使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热门文章

北端:融合系统,解释
1 个月前By尊渡假赌尊渡假赌尊渡假赌
Mandragora:巫婆树的耳语 - 如何解锁抓钩
4 周前By尊渡假赌尊渡假赌尊渡假赌
<🎜>掩盖:探险33-如何获得完美的色度催化剂
2 周前By尊渡假赌尊渡假赌尊渡假赌

热工具

EditPlus 中文破解版

EditPlus 中文破解版

体积小,语法高亮,不支持代码提示功能

SublimeText3 Mac版

SublimeText3 Mac版

神级代码编辑软件(SublimeText3)

SublimeText3 英文版

SublimeText3 英文版

推荐:为Win版本,支持代码提示!

禅工作室 13.0.1

禅工作室 13.0.1

功能强大的PHP集成开发环境

SublimeText3汉化版

SublimeText3汉化版

中文版,非常好用