Questions in category: MySQL (MySQL)
软件 >> MySQL
<[1] [2] [3] [4] [5] >

11. [MySQL] 实验

Posted by haifeng on 2021-05-11 08:35:26 last update 2021-05-11 08:59:24 | Answers (1) | 收藏


请写一个C/C++程序, 调用 MySQL 的 week() 函数或其他函数, 返回第几周. 当然, 这个程序可以设定哪个是第一周.

目的: 练习 C/C++ 与 MySQL 的连接.

 


 如果不使用 MySQL , 如何解决?

 

问题:
学校有的课程是单双周排课的. 因此给老师和同学会带来一些不便, 时间长了会忘记第几周。
请写一个小程序, 可以用 C/C++ 或 Java 等语言, 返回当天所在是第几周。
鼓励最后做成手机 APP (安卓或苹果系统用)
------------------------------------------------
Exercise:

写一个 C/C++ 程序, 返回当天所在是第几周. 年份不影响结果.  例如:
xxxx-01-01   --->  第 0 周
xxxx-01-07   --->  第 1 周
依次类推

要求: 
  1. 设定某个日期所在的周是(开学)第一周, 比如 2021-03-01; (事实上, 可以只输入 03-01 或其他格式, 如: 3.1)
  2. 输入日期, 返回第几周. 如果输入的日期在 2021-03-01 前, 则返回0或负整数.
  3. 如果不输入日期参数, 则返回系统当天所在第几周.

 

12. 将某个表拆转成另一个表

Posted by haifeng on 2021-04-20 11:21:02 last update 2021-04-25 10:54:51 | Answers (1) | 收藏


现在在数据库 test 下有一张表 city. 内容如下

CityName
Hyderabad, India
San Francisco, USA
Sydney, Australia

 

现在要求将该表重新设计, 模式为 city2(name, country), 并且将数据自动存储到新表 city2 中.

 

假设 city 表中的数据非常多, 只能使用 MySQL 自带的工具.

 


[Hint]

使用 MySQL 自带的函数 SUBSTRING_INDEX.

 

mysql> SELECT SUBSTRING_INDEX(CityName,',',1) FROM city;
+---------------------------------+
| SUBSTRING_INDEX(CityName,',',1) |
+---------------------------------+
| Hyderabad                       |
| San Francisco                   |
| Sydney                          |
+---------------------------------+
3 rows in set (0.00 sec)

 

13. 在 MySQL 中替换字符串

Posted by haifeng on 2021-04-20 11:08:44 last update 2021-04-20 11:08:44 | Answers (0) | 收藏


假设 question 表的 link 属性(字段)是如下数据

link
http://www.atzjg.net/admin/do/listqsbyctgry.php?cid=18
http://www.atzjg.net/admin/do/listqsbyctgry.php?cid=101
http://www.atzjg.net/admin/do/listqsbyctgry.php?cid=50
http://www.atzjg.net/admin/do/listqsbyctgry.php?cid=25
...

 

显然, 这里的内容有太多重复, 请将 link 属性的内容简化为

link
18
101
50
25
...

 

请使用 MySQL 的内部函数实现.

 

14. 如何将某个表的结构存储到另一张表中?

Posted by haifeng on 2021-04-20 10:50:51 last update 2021-04-20 10:50:51 | Answers (0) | 收藏


在 MySQL 的样例 world_x 数据库中, 查询 city 表的结构可以使用 DESC city; 或者

SHOW CREATE TABLE city;

查看. 

现在, 要求将所查到的内容记录到一张表中. 请写出解决方案.

15. 使用 mysqlsh 登陆 mysql

Posted by haifeng on 2021-03-23 10:30:00 last update 2021-03-23 10:30:00 | Answers (0) | 收藏


在 mysqlsh 下, \c 是 \connect 命令, 用于连接数据库

 MySQL  JS > \c localhost root@localhost
\connect [--mx|--mysqlx|--mc|--mysql] <URI>
 MySQL  JS > \c --mysql root@localhost
Creating a Classic session to 'root@localhost'
Please provide the password for 'root@localhost': ******
Save password for 'root@localhost'? [Y]es/[N]o/Ne[v]er (default No):
Fetching schema names for autocompletion... Press ^C to stop.
Your MySQL connection id is 51
Server version: 5.7.23 MySQL Community Server (GPL)
No default schema selected; type \use <schema> to set one.
 MySQL  localhost:3306  JS >

 

16. mysql.exe 使用 -e 选项执行命令

Posted by haifeng on 2020-11-10 11:36:35 last update 2020-11-10 11:36:35 | Answers (0) | 收藏


当使用 msyql.exe 及选项 -e 执行命令时, 必须要加双引号. (单引号以及`` 都不行)

C:\Users\Administrator>mysql -uroot -p -e show databases
Enter password: ******
ERROR 1049 (42000): Unknown database 'databases'

 

C:\Users\Administrator>mysql -uroot -p -e "show databases"
Enter password: ******
+-------------------------+
| Database                |
+-------------------------+
| information_schema      |
| math                    |
| mysql                   |
| performance_schema      |
| test                    |
| test_bar                |
| test_electronicproducts |
| test_shipsinww2         |
+-------------------------+

17. mysql.exe 命令之用法

Posted by haifeng on 2020-11-10 11:26:17 last update 2020-11-10 11:26:17 | Answers (0) | 收藏


mysql.exe 命令之用法


mysql  Ver 14.14 Distrib 5.6.17, for Win64 (x86_64)
Copyright (c) 2000, 2014, 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.
                      (Defaults to on; use --skip-auto-rehash to disable.)
  -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.
  --auto-vertical-output
                      Automatically switch to vertical output mode if the
                      result is wider than the terminal width.
  -B, --batch         Don't use history file. Disable interactive behavior.
                      (Enables --silent.)
  --bind-address=name IP address to bind to.
  --character-sets-dir=name
                      Directory for character set files.
  --column-type-info  Display column type information.
  -c, --comments      Preserve comments. Send comments to the server. The
                      default is --skip-comments (discard comments), enable
                      with --comments.
  -C, --compress      Use compression in server/client protocol.
  -#, --debug[=#]     This is a non-debug version. Catch this and exit.
  --debug-check       Check memory and open file usage at exit.
  -T, --debug-info    Print some debug info at exit.
  -D, --database=name Database to use.
  --default-character-set=name
                      Set the default character set.
  --delimiter=name    Delimiter to be used.
  --enable-cleartext-plugin
                      Enable/disable the clear text authentication plugin.
  -e, --execute=name  Execute command and quit. (Disables --force and history
                      file.)
  -E, --vertical      Print the output of a query (rows) vertically.
  -f, --force         Continue even if we get an SQL error.
  -G, --named-commands
                      Enable named commands. Named commands mean this program's
                      internal commands; see mysql> help . When enabled, the
                      named commands can be used from any line of the query,
                      otherwise only from the first line, before an enter.
                      Disable with --disable-named-commands. This option is
                      disabled by default.
  -i, --ignore-spaces Ignore space after function names.
  --init-command=name SQL Command to execute when connecting to MySQL server.
                      Will automatically be re-executed when reconnecting.
  --local-infile      Enable/disable LOAD DATA LOCAL INFILE.
  -b, --no-beep       Turn off beep on error.
  -h, --host=name     Connect to host.
  -H, --html          Produce HTML output.
  -X, --xml           Produce XML output.
  --line-numbers      Write line numbers for errors.
                      (Defaults to on; use --skip-line-numbers to disable.)
  -L, --skip-line-numbers
                      Don't write line number for errors.
  -n, --unbuffered    Flush buffer after each query.
  --column-names      Write column names in results.
                      (Defaults to on; use --skip-column-names to disable.)
  -N, --skip-column-names
                      Don't write column names in results.
  --sigint-ignore     Ignore SIGINT (CTRL-C).
  -o, --one-database  Ignore statements except those that occur while the
                      default database is the one named at the command line.
  -p, --password[=name]
                      Password to use when connecting to server. If password is
                      not given it's asked from the tty.
  -W, --pipe          Use named pipes to connect to server.
  -P, --port=#        Port number to use for connection or 0 for default to, in
                      order of preference, my.cnf, $MYSQL_TCP_PORT,
                      /etc/services, built-in default (3306).
  --prompt=name       Set the mysql prompt to this value.
  --protocol=name     The protocol to use for connection (tcp, socket, pipe,
                      memory).
  -q, --quick         Don't cache result, print it row by row. This may slow
                      down the server if the output is suspended. Doesn't use
                      history file.
  -r, --raw           Write fields without conversion. Used with --batch.
  --reconnect         Reconnect if the connection is lost. Disable with
                      --disable-reconnect. This option is enabled by default.
                      (Defaults to on; use --skip-reconnect to disable.)
  -s, --silent        Be more silent. Print results with a tab as separator,
                      each row on new line.
  --shared-memory-base-name=name
                      Base name of shared memory.
  -S, --socket=name   The socket file to use for connection.
  --ssl               Enable SSL for connection (automatically enabled with
                      other flags).
  --ssl-ca=name       CA file in PEM format (check OpenSSL docs, implies
                      --ssl).
  --ssl-capath=name   CA directory (check OpenSSL docs, implies --ssl).
  --ssl-cert=name     X509 cert in PEM format (implies --ssl).
  --ssl-cipher=name   SSL cipher to use (implies --ssl).
  --ssl-key=name      X509 key in PEM format (implies --ssl).
  --ssl-crl=name      Certificate revocation list (implies --ssl).
  --ssl-crlpath=name  Certificate revocation list path (implies --ssl).
  --ssl-verify-server-cert
                      Verify server's "Common Name" in its cert against
                      hostname used when connecting. This option is disabled by
                      default.
  -t, --table         Output in table format.
  --tee=name          Append everything into outfile. See interactive help (\h)
                      also. Does not work in batch mode. Disable with
                      --disable-tee. This option is disabled by default.
  -u, --user=name     User for login if not current user.
  -U, --safe-updates  Only allow UPDATE and DELETE that uses keys.
  -U, --i-am-a-dummy  Synonym for option --safe-updates, -U.
  -v, --verbose       Write more. (-v -v -v gives the table output format).
  -V, --version       Output version information and exit.
  -w, --wait          Wait and retry if connection is down.
  --connect-timeout=# Number of seconds before connection timeout.
  --max-allowed-packet=#
                      The maximum packet length to send to or receive from
                      server.
  --net-buffer-length=#
                      The buffer size for TCP/IP and socket communication.
  --select-limit=#    Automatic limit for SELECT when using --safe-updates.
  --max-join-size=#   Automatic limit for rows in a join when using
                      --safe-updates.
  --secure-auth       Refuse client connecting to server if it uses old
                      (pre-4.1.1) protocol.
                      (Defaults to on; use --skip-secure-auth to disable.)
  --server-arg=name   Send embedded server this as a parameter.
  --show-warnings     Show warnings after every statement.
  --plugin-dir=name   Directory for client-side plugins.
  --default-auth=name Default authentication client-side plugin to use.
  --histignore=name   A colon-separated list of patterns to keep statements
                      from getting logged into mysql history.
  --binary-mode       By default, ASCII '\0' is disallowed and '\r\n' is
                      translated to '\n'. This switch turns off both features,
                      and also turns off parsing of all clientcommands except
                      \C and DELIMITER, in non-interactive mode (for input
                      piped to mysql or loaded using the 'source' command).
                      This is necessary when processing output from mysqlbinlog
                      that may contain blobs.
  --connect-expired-password
                      Notify the server that this client is prepared to handle
                      expired password sandbox mode.

Default options are read from the following files in the given order:
C:\Windows\my.ini C:\Windows\my.cnf C:\my.ini C:\my.cnf C:\wamp\bin\mysql\mysql5.6.17\my.ini C:\wamp\bin\mysql\mysql5.6.17\my.cnf
The following groups are read: mysql client
The following options may be given as the first argument:
--print-defaults        Print the program argument list and exit.
--no-defaults           Don't read default options from any option file,
                        except for login file.
--defaults-file=#       Only read default options from the given file #.
--defaults-extra-file=# Read this file after the global files are read.
--defaults-group-suffix=#
                        Also read groups with concat(group, suffix)
--login-path=#          Read this path from the login file.

Variables (--variable-name=value)
and boolean options {FALSE|TRUE}  Value (after reading options)
--------------------------------- ----------------------------------------
auto-rehash                       FALSE
auto-vertical-output              FALSE
bind-address                      (No default value)
character-sets-dir                (No default value)
column-type-info                  FALSE
comments                          FALSE
compress                          FALSE
debug-check                       FALSE
debug-info                        FALSE
database                          (No default value)
default-character-set             auto
delimiter                         ;
enable-cleartext-plugin           FALSE
vertical                          FALSE
force                             FALSE
named-commands                    FALSE
ignore-spaces                     FALSE
init-command                      (No default value)
local-infile                      FALSE
no-beep                           FALSE
host                              (No default value)
html                              FALSE
xml                               FALSE
line-numbers                      TRUE
unbuffered                        FALSE
column-names                      TRUE
sigint-ignore                     FALSE
port                              3306
prompt                            mysql>
quick                             FALSE
raw                               FALSE
reconnect                         TRUE
shared-memory-base-name           (No default value)
socket                            /tmp/mysql.sock
ssl                               FALSE
ssl-ca                            (No default value)
ssl-capath                        (No default value)
ssl-cert                          (No default value)
ssl-cipher                        (No default value)
ssl-key                           (No default value)
ssl-crl                           (No default value)
ssl-crlpath                       (No default value)
ssl-verify-server-cert            FALSE
table                             FALSE
user                              root
safe-updates                      FALSE
i-am-a-dummy                      FALSE
connect-timeout                   0
max-allowed-packet                16777216
net-buffer-length                 16384
select-limit                      1000
max-join-size                     1000000
secure-auth                       TRUE
show-warnings                     FALSE
plugin-dir                        (No default value)
default-auth                      (No default value)
histignore                        (No default value)
binary-mode                       FALSE
connect-expired-password          FALSE

18. msyql客户端的帮助

Posted by haifeng on 2020-11-10 11:18:40 last update 2020-11-10 11:18:40 | Answers (0) | 收藏


登录mysql后, 键入 \h 或 help , 然后回车(按 Enter) 即显示如下内容.

 

mysql> \h

For information about MySQL products and services, visit:
   http://www.mysql.com/
For developer information, including the MySQL Reference Manual, visit:
   http://dev.mysql.com/
To buy MySQL Enterprise support, training, or other products, visit:
   https://shop.mysql.com/

List of all MySQL commands:
Note that all text commands must be first on line and end with ';'
?         (\?) Synonym for `help'.
clear     (\c) Clear the current input statement.
connect   (\r) Reconnect to the server. Optional arguments are db and host.
delimiter (\d) Set statement delimiter.
ego       (\G) Send command to mysql server, display result vertically.
exit      (\q) Exit mysql. Same as quit.
go        (\g) Send command to mysql server.
help      (\h) Display this help.
notee     (\t) Don't write into outfile.
print     (\p) Print current command.
prompt    (\R) Change your mysql prompt.
quit      (\q) Quit mysql.
rehash    (\#) Rebuild completion hash.
source    (\.) Execute an SQL script file. Takes a file name as an argument.
status    (\s) Get status information from the server.
tee       (\T) Set outfile [to_outfile]. Append everything into given outfile.
use       (\u) Use another database. Takes database name as argument.
charset   (\C) Switch to another charset. Might be needed for processing binlog with multi-byte charsets.
warnings  (\W) Show warnings after every statement.
nowarning (\w) Don't show warnings after every statement.

For server side help, type 'help contents'

mysql>

19. MySQL 中的注释符

Posted by haifeng on 2020-11-10 11:13:13 last update 2020-11-10 11:13:13 | Answers (0) | 收藏


mysql 中可以使用 #, --, 或 /* */ 作为注释符.

当使用 -- 作为注释符时, 必须注意后面至少要加一个空格符(可以是空格, tab, 换行符)

 

mysql> select 2--1;  #2--1指2减去-1, 在mysql中是合法的.
+------+
| 2--1 |
+------+
|    3 |
+------+
1 row in set (0.04 sec)

mysql> select 2-(-1);
+--------+
| 2-(-1) |
+--------+
|      3 |
+--------+
1 row in set (0.00 sec)

20. MySQL 中的会话变量(session variables)

Posted by haifeng on 2020-11-10 11:04:46 last update 2020-11-10 11:06:01 | Answers (0) | 收藏


在数据库 information_schema 中, 查询所有会话变量

mysql> select COUNT(*) from SESSION_VARIABLES;  # how many session variables
+-----------+
| COUNT( *) |
+-----------+
|       445 |
+-----------+
1 row in set, 1 warning (0.01 sec)

<[1] [2] [3] [4] [5] >