PDO Postgresql UTF8 charset

时间:2016-07-19 00:10:07

标签: php sql postgresql pdo character-encoding

我正在寻找一种使用UTF8字符集连接到postgresql数据库的方法。

目前,我必须在连接后发送查询请求以指定字符集。它根本不是最佳的......

    $connect = new \PDO("pgsql:host=$this->host;dbname=$this->base", $this->user, $this->pass);
    $connect->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);
    $connect->query("SET NAMES '$this->charset'");

MySQL允许在参数上传递一个表来指定字符集,我正在寻找相同的东西。

        $this->db = new \PDO("pgsql:host=$this->PARAM_hote;dbname=$this->PARAM_nom_bd", $this->PARAM_utilisateur, $this->PARAM_mot_passe, array(\PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES \'UTF8\''));
        $this->db->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);

3 个答案:

答案 0 :(得分:0)

尝试在构造函数中添加参数:

$connect = new \PDO("pgsql:host=$this->host;dbname=$this->base" . ";options='-c client_encoding=utf8'", $this->user, $this->pass);
$connect->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);

答案 1 :(得分:0)

与:

new PDO('pgsql:host=' .  $db_host . ';dbname=' . $db_name . ';options=\'--client_encoding=UTF8\'', $db_username, $db_password, array(PDO::ATTR_PERSISTENT => true));

事实上,传递选项-client_encoding = UTF8 的单引号非常重要,而双引号则无效。

答案 2 :(得分:0)

您可以像这样传递'options'键:

# items and their prices
items = {'banana': 3,
         'apple': 2,
         'milk': 12,
         'bread': 15,
         'orange': 3,
         'cheese': 14,
         'chicken': 42,
         'peanuts':32 ,
         'butter': 20,
         'cooldrink': 18,
         }
#Asking for the item

price = 0
while True:
    choice = input("Select your item(type 'nothing' to make it stop) \n : ")

    if choice == 'nothing':
        break

    if choice in items.keys():
        price += items[choice]
    else:
        print("Uh oh, I don't know about that item")

print('your result', price )

相关问题