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'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 'charset utf8)' 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='1.0',) 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 ('mysql','INFORMATION_SCHEMA') and character_set_name is not null""" #三个if条件实现过滤 if options.db_name: query += " and table_schema='%s'" % options.db_name if options.t_name: query += " and table_name='%s'" % options.t_name if options.c_name: query += " and column_name='%s'" % options.c_name #默认返回值形式是元组,我们通过属性cursors.DictCursor转为字典 cur = conn.cursor(MySQLdb.cursors.DictCursor) cur.execute(query) for record in cur.fetchall(): character_set_name = record['CHARACTER_SET_NAME'] collation_name = record['COLLATION_NAME'] print "%s.%s.%s:t%st%s" % (record['TABLE_SCHEMA'], record['TABLE_NAME'],record['COLUMN_NAME'],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'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='1.0',) return parser.parse_args() #主程序 def modify_column(): cur = conn.cursor(MySQLdb.cursors.DictCursor) v_sql = """ select * from information_schema.columns where table_schema='%s' and table_name='%s' and column_name='%s'""" % (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['COLUMN_TYPE'] column_default = row['COLUMN_DEFAULT'] is_nullable = (row['IS_NULLABLE'] == 'YES') 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 '%s'" % 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)!

MySQL 느린 쿼리를 최적화하려면 SlowQueryLog 및 Performance_Schema를 사용해야합니다. 1. SlowQueryLog 및 Set Stresholds를 사용하여 느린 쿼리를 기록합니다. 2. Performance_schema를 사용하여 쿼리 실행 세부 정보를 분석하고 성능 병목 현상을 찾고 최적화하십시오.

MySQL 및 SQL은 개발자에게 필수적인 기술입니다. 1.MySQL은 오픈 소스 관계형 데이터베이스 관리 시스템이며 SQL은 데이터베이스를 관리하고 작동하는 데 사용되는 표준 언어입니다. 2.MYSQL은 효율적인 데이터 저장 및 검색 기능을 통해 여러 스토리지 엔진을 지원하며 SQL은 간단한 문을 통해 복잡한 데이터 작업을 완료합니다. 3. 사용의 예에는 기본 쿼리 및 조건 별 필터링 및 정렬과 같은 고급 쿼리가 포함됩니다. 4. 일반적인 오류에는 구문 오류 및 성능 문제가 포함되며 SQL 문을 확인하고 설명 명령을 사용하여 최적화 할 수 있습니다. 5. 성능 최적화 기술에는 인덱스 사용, 전체 테이블 스캔 피하기, 조인 작업 최적화 및 코드 가독성 향상이 포함됩니다.

MySQL 비동기 마스터 슬레이브 복제는 Binlog를 통한 데이터 동기화를 가능하게하여 읽기 성능 및 고 가용성을 향상시킵니다. 1) 마스터 서버 레코드는 Binlog로 변경됩니다. 2) 슬레이브 서버는 I/O 스레드를 통해 Binlog를 읽습니다. 3) 서버 SQL 스레드는 데이터를 동기화하기 위해 Binlog를 적용합니다.

MySQL은 오픈 소스 관계형 데이터베이스 관리 시스템입니다. 1) 데이터베이스 및 테이블 작성 : CreateAbase 및 CreateTable 명령을 사용하십시오. 2) 기본 작업 : 삽입, 업데이트, 삭제 및 선택. 3) 고급 운영 : 가입, 하위 쿼리 및 거래 처리. 4) 디버깅 기술 : 확인, 데이터 유형 및 권한을 확인하십시오. 5) 최적화 제안 : 인덱스 사용, 선택을 피하고 거래를 사용하십시오.

MySQL의 설치 및 기본 작업에는 다음이 포함됩니다. 1. MySQL 다운로드 및 설치, 루트 사용자 비밀번호를 설정하십시오. 2. SQL 명령을 사용하여 CreateAbase 및 CreateTable과 같은 데이터베이스 및 테이블을 만듭니다. 3. CRUD 작업을 실행하고 삽입, 선택, 업데이트, 명령을 삭제합니다. 4. 성능을 최적화하고 복잡한 논리를 구현하기 위해 인덱스 및 저장 절차를 생성합니다. 이 단계를 사용하면 MySQL 데이터베이스를 처음부터 구축하고 관리 할 수 있습니다.

innodbbufferpool은 데이터와 색인 페이지를 메모리에로드하여 MySQL 데이터베이스의 성능을 향상시킵니다. 1) 데이터 페이지가 버퍼 풀에로드되어 디스크 I/O를 줄입니다. 2) 더러운 페이지는 정기적으로 디스크로 표시되고 새로 고침됩니다. 3) LRU 알고리즘 관리 데이터 페이지 제거. 4) 읽기 메커니즘은 가능한 데이터 페이지를 미리로드합니다.

MySQL은 설치가 간단하고 강력하며 데이터를 쉽게 관리하기 쉽기 때문에 초보자에게 적합합니다. 1. 다양한 운영 체제에 적합한 간단한 설치 및 구성. 2. 데이터베이스 및 테이블 작성, 삽입, 쿼리, 업데이트 및 삭제와 같은 기본 작업을 지원합니다. 3. 조인 작업 및 하위 쿼리와 같은 고급 기능을 제공합니다. 4. 인덱싱, 쿼리 최적화 및 테이블 파티셔닝을 통해 성능을 향상시킬 수 있습니다. 5. 데이터 보안 및 일관성을 보장하기위한 지원 백업, 복구 및 보안 조치.

전체 테이블 스캔은 MySQL에서 인덱스를 사용하는 것보다 빠를 수 있습니다. 특정 사례는 다음과 같습니다. 1) 데이터 볼륨은 작습니다. 2) 쿼리가 많은 양의 데이터를 반환 할 때; 3) 인덱스 열이 매우 선택적이지 않은 경우; 4) 복잡한 쿼리시. 쿼리 계획을 분석하고 인덱스 최적화, 과도한 인덱스를 피하고 정기적으로 테이블을 유지 관리하면 실제 응용 프로그램에서 최상의 선택을 할 수 있습니다.


핫 AI 도구

Undresser.AI Undress
사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover
사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool
무료로 이미지를 벗다

Clothoff.io
AI 옷 제거제

AI Hentai Generator
AI Hentai를 무료로 생성하십시오.

인기 기사

뜨거운 도구

SublimeText3 영어 버전
권장 사항: Win 버전, 코드 프롬프트 지원!

Atom Editor Mac 버전 다운로드
가장 인기 있는 오픈 소스 편집기

WebStorm Mac 버전
유용한 JavaScript 개발 도구

VSCode Windows 64비트 다운로드
Microsoft에서 출시한 강력한 무료 IDE 편집기

MinGW - Windows용 미니멀리스트 GNU
이 프로젝트는 osdn.net/projects/mingw로 마이그레이션되는 중입니다. 계속해서 그곳에서 우리를 팔로우할 수 있습니다. MinGW: GCC(GNU Compiler Collection)의 기본 Windows 포트로, 기본 Windows 애플리케이션을 구축하기 위한 무료 배포 가능 가져오기 라이브러리 및 헤더 파일로 C99 기능을 지원하는 MSVC 런타임에 대한 확장이 포함되어 있습니다. 모든 MinGW 소프트웨어는 64비트 Windows 플랫폼에서 실행될 수 있습니다.

뜨거운 주제



