数据库
首页 > 数据库> > sql-Create语句中的变量

sql-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='Uid=@username; Pwd=@password; Server=****; Port=3306; Database =****; Table=****;' ;

没用,仍然说格式不正确

解决方法:

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;

标签:variables,connection,sql,mysql,federated
来源: https://codeday.me/bug/20191024/1920439.html