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 mmocr的训练错误,结果全为0
  • ¥15 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀