2009-08-13 73 views
3

我想在數據庫中設置一個創建腳本使用一些變量。我不確定如何使用它們。請解釋如何正確格式化我的代碼。下面是我嘗試的代碼,和錯誤,我得到:變量在CREATE語句

SET @username = 'xxxx'; -- store number goes here 
SET @password = 'xxxxxx'; -- store password goes here 

CREATE TABLE IF NOT EXISTS `my_table` (
`id` int(11) auto_increment, 
`release_date` datetime, 
`front_image_file` varchar(255), 
PRIMARY KEY (`id`) 
) ENGINE=FEDERATED 
DEFAULT CHARSET=latin1 
AUTO_INCREMENT=1 
CONNECTION='mysql://`@username`:`@password`@host_name:3306/database_name/table_tame' ; 

錯誤

#1432 - Can't create federated table. The data source connection string 'mysql://`@username`:`@password`@host_name:3306/databa' is not in the correct format 

我也試了一下沒有`

試圖EdmundG的解決方案

SET @username = 'xxxx'; -- store number goes here 
SET @password = 'xxxxxx'; -- store password goes here 

CREATE TABLE IF NOT EXISTS `my_table` (
`id` int(11) auto_increment, 
`release_date` datetime, 
`front_image_file` varchar(255), 
PRIMARY KEY (`id`) 
) ENGINE=FEDERATED 
DEFAULT CHARSET=latin1 
AUTO_INCREMENT=1 
CONNECTION='[email protected]; [email protected]; Server=****; Port=3306; Database =****; Table=****;' ; 

沒「T工作,仍然說沒有正確格式化

回答

0

行第三次嘗試。

有兩個可能的問題,我可以看到。

  1. 您在SQL中有正確的引號而不是 通用單引號。

  2. 您需要定義變量 並在運行使用這些變量的SQL 之前執行。

http://www.connectionstrings.com/mysql

+0

我從http://dev.mysql.com/doc/refman/5.0/en/federated-use.html獲得了連接字符串,並且在沒有變量的情況下它工作正常。如果你可以把整個事情對我來說,這將是真棒 – 2009-08-13 18:25:48

+0

我不知道這是去上班。你不需要將整個命令包裝在一個字符串中並使用EXEC調用嗎? – 2009-08-13 18:37:44

+0

當然,這個評論來自SqlServer世界中的某個人;也許它在MySQL中是不同的。 – 2009-08-13 18:39:23

0

如果你正在使用MySQL 5+你能不能儘量把它放在一個存儲功能,然後運行該功能?

0

你不能做到這一點。 mysql不解析變量的DDL語句。

0

試試這個

SET @username = 'XXXX'; - 門店數量到這裏

SET @密碼= 'XXXXXX'; - 存儲密碼放在這裏

CREATE TABLE IF NOT EXISTS my_table (
id int(11) AUTO_INCREMENT, 
release_date datetime, 
front_image_file varchar(255), 
PRIMARY KEY (id)) 
ENGINE=FEDERATED 
DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 CONNECTION='Uid='[email protected]'; Pwd='[email protected]+'; Server=****; Port=3306; Database =****'; 
5

的MySQL不支持直接將變量插入到類似的語法中。

你可以,但是,建立與這些變量的字符串,然後準備和執行它作爲dynamic SQL

SET @username = 'xxxx'; -- store number goes here 
SET @password = 'xxxxxx'; -- store password goes here 

SET @sql = CONCAT('CREATE TABLE IF NOT EXISTS `my_table` (', 
    ' `id` int(11) auto_increment,', 
    ' `release_date` datetime,', 
    ' `front_image_file` varchar(255),', 
    ' PRIMARY KEY (`id`)', 
    ') ENGINE=FEDERATED', 
    ' DEFAULT CHARSET=latin1', 
    ' AUTO_INCREMENT=1', 
    ' CONNECTION=''mysql://', @username, ':', @password, 
    '@host_name:3306/database_name/table_tame'); 

PREPARE stmt FROM @sql; 

EXECUTE stmt; 

DEALLOCATE stmt;