drygauost253590142 2014-04-09 15:48
浏览 63
已采纳

PDO似乎没有创建MySQL数据库

I'm trying to create a database using the following code:

// Set up DB connection and creates the DB
try {

    $connection = new \PDO(
            'mysql:host='.Settings\Database::$host.';',
            Settings\Database::$username,
            Settings\Database::$password);

    $connection->exec("CREATE DATABASE IF NOT EXISTS ".Settings\Database::$databaseName." CHARACTER SET utf8 COLLATION utf8_unicode_ci;");
} catch (\PDOException $exception) {

    die("Could not connect to database: ".$exception->getMessage());
}

The problem is that no database is being created and I receive no error except for the fact that when I try create a table with PDO i receive this error:

READ EDIT 2

Could not connect to database: SQLSTATE[HY000] [1049] Unknown database 'dbname'

Edit:

I have no problem manually creating the DB with phpMyAdmin and similars.

Edit 2:

Mistakenly I thought that the error was given by the CREATE TABLE... statement. Instead the error is returned by the die() function in the exception handling.

  • 写回答

1条回答 默认 最新

  • douruocai4111 2014-04-09 16:17
    关注

    Your call to exec() isn't throwing exceptions. You have to enable that for each PDO connection with an attribute like this:

    $connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    

    If you were getting the error message from exec(), you would have seen this:

    Could not connect to database: SQLSTATE[42000]: Syntax error or access violation: 1064 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 'COLLATION utf8_unicode_ci' at line 1

    The syntax for CREATE DATABASE uses the keyword COLLATE, not COLLATION.

    See http://dev.mysql.com/doc/refman/5.6/en/create-database.html

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 求差集那个函数有问题,有无佬可以解决
  • ¥15 MATLAB动图问题
  • ¥15 【提问】基于Invest的水源涵养
  • ¥20 微信网友居然可以通过vx号找到我绑的手机号
  • ¥15 寻一个支付宝扫码远程授权登录的软件助手app
  • ¥15 解riccati方程组
  • ¥15 display:none;样式在嵌套结构中的已设置了display样式的元素上不起作用?
  • ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
  • ¥50 树莓派安卓APK系统签名