Home Database Mysql Tutorial MySQLSchema设计(五)用Python管理字符集_MySQL

MySQLSchema设计(五)用Python管理字符集_MySQL

May 27, 2016 pm 02:12 PM

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)
Copy after login
㈠ 显示字符集
Copy after login
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)
Copy after login
[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
Copy after login
[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)
Copy after login
[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
Copy after login
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()
Copy after login

㈡ 修改列的字符集

[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
Copy after login
#修改前 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()
Copy after login

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


Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What is the reason why PS keeps showing loading? What is the reason why PS keeps showing loading? Apr 06, 2025 pm 06:39 PM

PS "Loading" problems are caused by resource access or processing problems: hard disk reading speed is slow or bad: Use CrystalDiskInfo to check the hard disk health and replace the problematic hard disk. Insufficient memory: Upgrade memory to meet PS's needs for high-resolution images and complex layer processing. Graphics card drivers are outdated or corrupted: Update the drivers to optimize communication between the PS and the graphics card. File paths are too long or file names have special characters: use short paths and avoid special characters. PS's own problem: Reinstall or repair the PS installer.

How to solve the problem of loading when PS is started? How to solve the problem of loading when PS is started? Apr 06, 2025 pm 06:36 PM

A PS stuck on "Loading" when booting can be caused by various reasons: Disable corrupt or conflicting plugins. Delete or rename a corrupted configuration file. Close unnecessary programs or upgrade memory to avoid insufficient memory. Upgrade to a solid-state drive to speed up hard drive reading. Reinstalling PS to repair corrupt system files or installation package issues. View error information during the startup process of error log analysis.

How to speed up the loading speed of PS? How to speed up the loading speed of PS? Apr 06, 2025 pm 06:27 PM

Solving the problem of slow Photoshop startup requires a multi-pronged approach, including: upgrading hardware (memory, solid-state drive, CPU); uninstalling outdated or incompatible plug-ins; cleaning up system garbage and excessive background programs regularly; closing irrelevant programs with caution; avoiding opening a large number of files during startup.

How to solve the problem of loading when the PS opens the file? How to solve the problem of loading when the PS opens the file? Apr 06, 2025 pm 06:33 PM

"Loading" stuttering occurs when opening a file on PS. The reasons may include: too large or corrupted file, insufficient memory, slow hard disk speed, graphics card driver problems, PS version or plug-in conflicts. The solutions are: check file size and integrity, increase memory, upgrade hard disk, update graphics card driver, uninstall or disable suspicious plug-ins, and reinstall PS. This problem can be effectively solved by gradually checking and making good use of PS performance settings and developing good file management habits.

How to solve the problem of loading when PS is always showing that it is loading? How to solve the problem of loading when PS is always showing that it is loading? Apr 06, 2025 pm 06:30 PM

PS card is "Loading"? Solutions include: checking the computer configuration (memory, hard disk, processor), cleaning hard disk fragmentation, updating the graphics card driver, adjusting PS settings, reinstalling PS, and developing good programming habits.

How does PS feathering control the softness of the transition? How does PS feathering control the softness of the transition? Apr 06, 2025 pm 07:33 PM

The key to feather control is to understand its gradual nature. PS itself does not provide the option to directly control the gradient curve, but you can flexibly adjust the radius and gradient softness by multiple feathering, matching masks, and fine selections to achieve a natural transition effect.

How to use mysql after installation How to use mysql after installation Apr 08, 2025 am 11:48 AM

The article introduces the operation of MySQL database. First, you need to install a MySQL client, such as MySQLWorkbench or command line client. 1. Use the mysql-uroot-p command to connect to the server and log in with the root account password; 2. Use CREATEDATABASE to create a database, and USE select a database; 3. Use CREATETABLE to create a table, define fields and data types; 4. Use INSERTINTO to insert data, query data, update data by UPDATE, and delete data by DELETE. Only by mastering these steps, learning to deal with common problems and optimizing database performance can you use MySQL efficiently.

What should I do if the PS card is in the loading interface? What should I do if the PS card is in the loading interface? Apr 06, 2025 pm 06:54 PM

The loading interface of PS card may be caused by the software itself (file corruption or plug-in conflict), system environment (due driver or system files corruption), or hardware (hard disk corruption or memory stick failure). First check whether the computer resources are sufficient, close the background program and release memory and CPU resources. Fix PS installation or check for compatibility issues for plug-ins. Update or fallback to the PS version. Check the graphics card driver and update it, and run the system file check. If you troubleshoot the above problems, you can try hard disk detection and memory testing.

See all articles