开发者

How can I set mysql charset at connection time using doctrine?

I'm trying to set the charset to utf8 when I connect to a database using Doctrine. I can do it fine if I connect using a regular PDO connection like this:

$manager = Doctrine_Manager::getInstance();

$manager->connection(
    array(
        'mysql:dbname=mydb;host=127.0.0.1;',
        'user',
        'password',
        array( PDO::ATTR_PERSISTENT => true, PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES 'utf8';" )
        ),
    'doctrine' );

The problem I have with this is that I can't drop the database unless I use a Doctrine-like dsn. Something like this:

$manager->connection('mysql://user:password@127.0.0.1/mydb', 'doctrine' );

But, if I do it like this I can't set the PDO attributes right from the start (at connection time), I have to use:

$manager->getConnection( 'viajeros_doctrine' )->setCharset('utf8');
$manager->getConnection( 'viajeros_doctrine' )->set开发者_Go百科Attribute(Doctrine_Core::ATTR_PERSISTENT, true);

Now, I'm not sure whether this is worse from a performance point of view (I mean, I don't know exactly what PDO does with it's parameters when you create a new object, but I think I'm issuing a useless query everytime I get connected to the database (SET NAMES='UTF8').

From what I read at http://www.doctrine-project.org/documentation/manual/1_1/en/introduction-to-connections, I should use something like:

$manager->connection('mysql://user:password@127.0.0.1/mydb?charset=utf8', 'doctrine' );

But going through Doctrine code with a debugger, I see that the charset part of the dsn gets parsed, but I can't see it being used anywhere...

So, am I doing something wrong here? Thanks.


You should pass the charset with the connection in a fully assoc array: http://docs.doctrine-project.org/projects/doctrine-dbal/en/latest/reference/configuration.html#pdo-mysql

Setting the charset using SET NAMES after building the connection is wrong. It will cause mysqli real_escape to improperly escape characters.

It will be parsed as an assoc array: http://www.tig12.net/downloads/apidocs/symfony/lib/plugins/sfDoctrinePlugin/lib/vendor/doctrine/Doctrine/Manager.php.source.html#line221

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜