MySQL基础:程序中调用mysql的方法

MySQL基础:程序中调用mysql的方法_第1张图片
在Oracle通过sqlplus可以连接数据库根据用户权限进行数据或者设定操作,但是需要交互操作并返回结果的情况可以使用HereDocument等方式予以解决,这篇文章介绍一下如何在程序中使用MySQL的终端控制台。

环境准备

环境准备可参看:

  • MySQL环境搭建与简单使用: Docker方式
  • macOS上搭建MySQL环境

注:已有MySQL的可以跳过此步骤。

使用场景

假定需要获取MySQL的版本,需要在控制台上输入select version()然后回车获得版本信息(当然其他方法更快,比如mysql --version,此处主要为模拟场景),使用MySQL控制台的方法一般如下所示:

liumiaocn:~ liumiao$ mysql -uroot -proot
mysql: [Warning] Using a password on the command line interface can be insecure.
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 31
Server version: 8.0.11 Homebrew

Copyright (c) 2000, 2018, 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.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

mysql> select version();
+-----------+
| version() |
+-----------+
| 8.0.11    |
+-----------+
1 row in set (0.00 sec)

mysql>

方式1: Here Document

因为mysql是控制台的方式与用户进行交互式的输入/输出对应,而在程序执行的过程中显然是需要预先定好的输入,这样可以考虑使用Here Document,比如希望通过mysql来确认数据库版本信息,则可以这样

liumiaocn:~ liumiao$ mysql -uroot -proot < select version();
> EOF
mysql: [Warning] Using a password on the command line interface can be insecure.
version()
8.0.11
liumiaocn:~ liumiao$

方式2: 使用-e选项

mysql命令可以使用-e参数传入要执行的命令,如果多条命令时需要写成一行,如果可以接受阅读上的问题,比较简单的情况使用-e无疑更为方便,比如使用select version()获取版本的类似情况只需要一行即可解决。

liumiaocn:~ liumiao$ mysql -uroot -proot -e "select version()"
mysql: [Warning] Using a password on the command line interface can be insecure.
+-----------+
| version() |
+-----------+
| 8.0.11    |
+-----------+
liumiaocn:~ liumiao$ 

为了解决代码阅读上的不整齐规范的情绪,可以使用如下方式来解决,这样多条命令也不必写成一行,算是一个折衷方法。

liumiaocn:~ liumiao$ cat get_mysql_version.sh 
#!/bin/sh

mysql -uroot -proot -e "\
select version();       \
select version();       \
select version();"
liumiaocn:~ liumiao$ 
liumiaocn:~ liumiao$ sh get_mysql_version.sh 
mysql: [Warning] Using a password on the command line interface can be insecure.
+-----------+
| version() |
+-----------+
| 8.0.11    |
+-----------+
+-----------+
| version() |
+-----------+
| 8.0.11    |
+-----------+
+-----------+
| version() |
+-----------+
| 8.0.11    |
+-----------+
liumiaocn:~ liumiao$

总结

sqlplus结合Here Document即可实现在程序中调用sqlplus。

你可能感兴趣的:(数据库)