2013-04-19 16 views
1

我已將sqlite數據庫轉換爲mysql。如何使用PHP將sqlite轉換爲mysql

因此,我需要將sqlite + php代碼轉換爲mysql + php代碼。你有任何包含方法將sqlite轉換爲mysql的文檔。

感謝..

這是我的代碼

<?php 

try { 
    //open the database 
    $db = new PDO('sqlite:cars.sqlite'); //will create the file in current directory. Current directory must be writable 

    //create the database if does not exist 
    $db->exec("CREATE TABLE IF NOT EXISTS cars (id INTEGER PRIMARY KEY, manufacturer TEXT, year INTEGER, price INTEGER)"); 

    //select all data from the table 
    $select = $db->prepare('SELECT * FROM cars ORDER BY id ASC LIMIT 100'); 
    $select->execute(); 

    $out = array(
    'cars' => $select->fetchAll(PDO::FETCH_ASSOC) 
); 
    echo json_encode($out); 

    // close the database connection 
    $db = NULL; 
} 
catch (PDOException $e) { 
    print 'Exception : ' . $e->getMessage(); 
} 
?> 

MySQL表:汽車

CREATE TABLE IF NOT EXISTS `cars` (
    `id` int(11) NOT NULL DEFAULT '0', 
    `manufacturer` text, 
    `year` int(11) DEFAULT '0', 
    `price` text, 
    PRIMARY KEY (`id`) 
) ENGINE=InnoDB DEFAULT CHARSET=utf8; 

回答

2

與您使用PDO,剛剛創建MySQL PDO目標CT,改變這一部分:

$db = new PDO('sqlite:cars.sqlite'); 

喜歡的東西:

$dsn = 'mysql:dbname=yourdbname;host=127.0.0.1'; 
$user = 'yourdbuser'; 
$password = 'yourdbpass'; 
$dbh = new PDO($dsn, $user, $password); 

就大功告成了。你不需要改變其他任何東西。

PDO是便攜式連接對象,它可以與幾個不同的數據庫一起使用。更多關於PDO:http://php.net/manual/en/pdo.construct.php

+0

我加了下面的db連接,$ con = mysql_connect(「localhost」,「root」,「」)或die(「error1」); $ db = mysql_select_db(「decsys」,$ con)或死(「error2」) –

+0

不!你已經在使用PDO。繼續使用它! 'mysql_connect'和朋友已被棄用,並且很快就會被移除。看到我更新的答案? – egig

+0

非常感謝Mr.Charlie。你救了我的一天! –