我正在创建一个包含 NOT NULL 列的表,如下所示:
CREATE TABLE IF NOT EXISTS Users (Id INTEGER PRIMARY KEY, Username TEXT UNIQUE NOT NULL, Password TEXT NOT NULL);
但 SQLite 很乐意为这些列添加 NULL 值:
<?php
error_reporting(E_ALL);
date_default_timezone_set('Europe/Helsinki');
ini_set('default_charset', 'UTF-8');
mb_internal_encoding("UTF-8");
header('Content-Type: text/html; charset=UTF-8');
// ---
const DB_FILE = "auth.db";
//$username = "john";
//$password = "secret";
$username = '';
$password = '';
// ---
// open db
//$db = new PDO('sqlite:'.DB_FILE);
$db = new PDO('sqlite::memory:');
// set attributes
$db->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
// create the table
$db->exec("CREATE TABLE IF NOT EXISTS Users (Id INTEGER PRIMARY KEY, Username TEXT UNIQUE NOT NULL, Password TEXT NOT NULL);");
$statement = "INSERT INTO Users (Username, Password) VALUES (:Username,:Password);";
$query = $db->prepare($statement);
$query->bindValue(':Username', $username, SQLITE3_TEXT);
$query->bindValue(':Password', $password, SQLITE3_TEXT);
$ok = $query->execute();
$result = $db->query('SELECT * FROM Users');
if (!$result) die ("oops!"); // will not produce anything when errormode is on
echo "<pre>\n";
foreach($result as $row)
{
echo "Id: " . $row['Id'] . "\n";
echo "Username: " . $row['Username'] . "\n";
echo "Password: " . $row['Password'] . "\n";
}
$db = NULL;
?>
SQLite 不应该允许这样做。我究竟做错了什么?
更新于 2013-04-23 ~00:35 Z
以下是对 Diamond Geezer 回答的评论。
SQLite 停止执行这些语句:
$db->exec("INSERT INTO Users (Username, Password) VALUES ('','');");
$db->exec("INSERT INTO Users (Username, Password) VALUES ('a','aa');");
$db->exec("SELECT * FROM Users;");
但不是这些:
$username = '';
$password = '';
$statement = "INSERT INTO Users (Username, Password) VALUES (:Username,:Password);";
$query = $db->prepare($statement);
$query->bindValue(':Username', $username, SQLITE3_TEXT);
$query->bindValue(':Password', $password, SQLITE3_TEXT);
$ok = $query->execute();
我认为这一定与准备声明有关。