Bash-MySQL /尝试将字符串插入表中

时间:2013-06-10 16:10:24

标签: mysql linux bash

我尝试在bash中将字符串插入mysql,所以我会做下一个:

message="<a href = http://www."
message="$message ${d}"
message="$message .com"
mysql -u root -pmypass -Bse 'INSERT INTO atTable VALUES (null, "'$message'")'

当我这样做时,我会接受下一次按摩:

mysql  Ver 14.14 Distrib 5.1.69, for debian-linux-gnu (i486) using readline 6.1
Copyright (c) 2000, 2013, Oracle and/or its affiliates. All rights reserved.

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.

Usage: mysql [OPTIONS] [database]
  -?, --help          Display this help and exit.
  -I, --help          Synonym for -?
  --auto-rehash       Enable automatic rehashing. One doesn't need to use
                      'rehash' to get table and field completion, but startup
                      and reconnecting may take a longer time. Disable with
                      --disable-auto-rehash.
  -A, --no-auto-rehash
                      No automatic rehashing. One has to use 'rehash' to get
                      table and field completion. This gives a quicker start of
                      mysql and disables rehashing on reconnect.
  -B, --batch         Don't use history file. Disable interactive behavior.
                      (Enables --silent.)
  --character-sets-dir=name
                      Directory for character set files.

和其他命令。我做错了什么?

3 个答案:

答案 0 :(得分:1)

请试试这个:

message="<a href = http://www."
message="$message ${d}"
message="$message .com"
mysql -u root -pmypass -Bse "INSERT INTO atTable VALUES (null, '$message')";

至少它对我有用,当我用它测试它时:

message="<a href = http://www."
message="$message hello"
message="$message .com"
mysql -u root -pwhatever -Bse "SELECT '$message'";

答案 1 :(得分:1)

试试这个:

mysql -u root -pmypass -Bse "INSERT INTO atTable VALUES (null, '$message')"

问题是$message中的空格结束了-e选项。

答案 2 :(得分:0)

  1. 而不是像你一样拼凑message变量,这更容易理解:

    message="<a href = http://www. $d .com"
    

    这相当于原帖中的示例,但文本本身看起来并没有意义。

  2. 您可以将查询传递给mysql,如下所示:

    mysql -u root -pmypass -Bse  "INSERT INTO atTable VALUES (null, '$message')"
    
  3. 如果message包含单引号,则需要转义它们,您可以这样做:

    message=$(echo "$message" | sed -e "s/'/\\\\'/")
    
  4. 我建议将这些信息放在主目录的.my.cnf文件中,而不是将root密码放在命令行上,例如:

    [client]
    database=yourdbname
    user=root
    password=yourpass
    

    然而,在输入真实密码之前 ,请首先保护文件:

    touch .my.cnf
    chmod 600 .my.cnf