简体   繁体   中英

MySQL, Python - Latin-1/UTF8 Encoding

I have read around setting MySQL tables/DB to UTF8_general_ci charset from the default latin-1 where I was having an error inserting particular unicode strings into the MySQL table from my Python script. I deleted the entire DB, and recreated it with:

CREATE DATABASE dbname CHARACTER SET utf8 COLLATE utf8_general_ci;

And I then created my tables within this schema appended with:

ENGINE=InnoDB  DEFAULT CHARSET=utf8 AUTO_INCREMENT=1;

I have a Python script feeding into the table(s) with the MySQLdb driver, I have specified the charset at the beginning of the script with:

connectToDb = mdb.connect(host="localhost",
                          user="me",
                          passwd="me",
                          db="me",
                          charset="utf8",
                          use_unicode=True)

Records feed into the DB tables without encoding error. My problem is that I have a DB driven intranet site (using PHP script to make the table entry) running from these records and a number of the records in the <td> 's are sohwing as containing glyphs when I use Chrome to the web page.

I have specified my PHP connection in the HTML of the page as:

$connect = mysql_connect("localhost",$usrname,$password,"charset='utf8'");

In particular the GB "£" symbol is causing the offence (when I check PHPmyadmin I can see that it is a "£" symbol in the GUI).

I do not know what the cause is, can you help? Thanks.

EDIT: The HTML page also has the following declared:

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />

1.Remove "charset='utf8'" from mysql_connect - it is incorrect.

2.Try using mysql_set_charset after connecting

$connect = mysql_connect('localhost', $user, $password);
mysql_set_charset('utf8', $connect);

PS

mysql_* functions are deprecated, don't use them. Consider switching to PDO or MySQLi.

From @guybennet: replacing characters with UTF-8 after using mysql_set_charset('utf8') function

mysql_query("SET NAMES 'utf8'");
mysql_query("SET CHARACTER SET utf8");
mysql_query("SET COLLATION_CONNECTION = 'utf8_unicode_ci'");
and use utf-8 charset in all of your pages.

and the use of:

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM