板凳-------Mysql cookbook學習 (十一--------1)

第11章:生成和使用序列
11.0 引言

11.1 創建一個序列列并生成序列值

CREATE TABLE insect (
id INT UNSIGNED NOT NULL AUTO_INCREMENT,
PRIMARY KEY (id),name VARCHAR(30) NOT NULL,date DATE NOT NULL,origin VARCHAR(30) NOT NULL);
字段說明
?id?:主鍵,自動遞增。
?name?:字符串類型,存儲昆蟲的名稱。
?date?:日期類型,存儲采集日期。
?origin?:字符串類型,存儲采集地點。mysql> select * from insect;
+----+-------------------+------------+------------------+
| id | name              | date       | origin           |
+----+-------------------+------------+------------------+
|  1 | housefly          | 2014-09-10 | kitchen          |
|  2 | millipede         | 2014-09-10 | driveway         |
|  3 | grasshopper       | 2014-09-10 | front yard       |
|  4 | stink bug         | 2014-09-10 | front yard       |
|  5 | cabbage butterfly | 2014-09-10 | garden           |
|  6 | ant               | 2014-09-10 | back yard        |
|  7 | ant               | 2014-09-10 | back yard        |
|  8 | termite           | 2014-09-10 | kitchen woodwork |
+----+-------------------+------------+------------------+
8 rows in set (0.01 sec)mysql> describe insect;
+--------+--------------+------+-----+---------+----------------+
| Field  | Type         | Null | Key | Default | Extra          |
+--------+--------------+------+-----+---------+----------------+
| id     | int unsigned | NO   | PRI | NULL    | auto_increment |
| name   | varchar(30)  | NO   |     | NULL    |                |
| date   | date         | NO   |     | NULL    |                |
| origin | varchar(30)  | NO   |     | NULL    |                |
+--------+--------------+------+-----+---------+----------------+
4 rows in set (0.04 sec)id 字段是自增主鍵(auto_increment),這意味著 MySQL 會自動為新記錄分配唯一的 ID 值。
更新現有記錄:如果需要修改 ID 為 3 的記錄,使用UPDATE語句:
sql
UPDATE insect 
SET name = 'cricket', date = '2014-09-10', origin = 'basement' 
WHERE id = 3;
忽略重復:如果允許重復數據,可以使用INSERT IGNORE(但會靜默失敗):
sql
INSERT IGNORE INTO insect (id, name, date, origin) 
VALUES (3, 'cricket', '2014-09-10', 'basement');替換數據:使用REPLACE INTO覆蓋現有記錄:
sql
REPLACE INTO insect (id, name, date, origin) 
VALUES (3, 'cricket', '2014-09-10', 'basement');

11.2 為序列列選擇數據類型

11.3 序列生成的行刪除的效果

mysql> select * from insect order by id;
+----+-------------------+------------+------------------+
| id | name              | date       | origin           |
+----+-------------------+------------+------------------+
|  1 | housefly          | 2014-09-10 | kitchen          |
|  2 | millipede         | 2014-09-10 | driveway         |
|  3 | grasshopper       | 2014-09-10 | front yard       |
|  4 | stink bug         | 2014-09-10 | front yard       |
|  5 | cabbage butterfly | 2014-09-10 | garden           |
|  6 | ant               | 2014-09-10 | back yard        |
|  7 | ant               | 2014-09-10 | back yard        |
|  8 | termite           | 2014-09-10 | kitchen woodwork |
+----+-------------------+------------+------------------+
8 rows in set (0.00 sec)mysql> delete from insect where id in(2, 6);
Query OK, 2 rows affected (0.01 sec)mysql> select * from insect order by id;
+----+-------------------+------------+------------------+
| id | name              | date       | origin           |
+----+-------------------+------------+------------------+
|  1 | housefly          | 2014-09-10 | kitchen          |
|  3 | grasshopper       | 2014-09-10 | front yard       |
|  4 | stink bug         | 2014-09-10 | front yard       |
|  5 | cabbage butterfly | 2014-09-10 | garden           |
|  7 | ant               | 2014-09-10 | back yard        |
|  8 | termite           | 2014-09-10 | kitchen woodwork |
+----+-------------------+------------+------------------+
6 rows in set (0.00 sec)mysql> delete from insect where id in(8);
Query OK, 1 row affected (0.01 sec)mysql> select * from insect order by id;
+----+-------------------+------------+------------+
| id | name              | date       | origin     |
+----+-------------------+------------+------------+
|  1 | housefly          | 2014-09-10 | kitchen    |
|  3 | grasshopper       | 2014-09-10 | front yard |
|  4 | stink bug         | 2014-09-10 | front yard |
|  5 | cabbage butterfly | 2014-09-10 | garden     |
|  7 | ant               | 2014-09-10 | back yard  |
+----+-------------------+------------+------------+
5 rows in set (0.00 sec)mysql> select engine from information_schema.tables-> where table_schema='cookbook' and table_name='insect';
+--------+
| ENGINE |
+--------+
| InnoDB |
+--------+
1 row in set (0.01 sec)mysql> alter table insect engine = MyISAM;
Query OK, 5 rows affected (0.12 sec)
Records: 5  Duplicates: 0  Warnings: 0mysql> select engine from information_schema.tables-> where table_schema='cookbook' and table_name='insect';
+--------+
| ENGINE |
+--------+
| MyISAM |
+--------+
1 row in set (0.00 sec)  

2025年6月29日星期日
11.4 查詢序列值

mysql> select * from  insect order by id;
+----+-------------------+------------+------------+
| id | name              | date       | origin     |
+----+-------------------+------------+------------+
|  1 | housefly          | 2014-09-10 | kitchen    |
|  3 | grasshopper       | 2014-09-10 | front yard |
|  4 | stink bug         | 2014-09-10 | front yard |
|  5 | cabbage butterfly | 2014-09-10 | garden     |
|  7 | ant               | 2014-09-10 | back yard  |
+----+-------------------+------------+------------+
5 rows in set (0.01 sec)mysql> delete from insect where id in (2, 6, 8);
Query OK, 0 rows affected (0.00 sec)mysql> alter table tbl_name engine = MyISAM;
Query OK, 6 rows affected (0.36 sec)
Records: 6  Duplicates: 0  Warnings: 0mysql> select engine from information_schema.tables-> where table_schema = 'cookbook' and table_name = 'insect';
+--------+
| ENGINE |
+--------+
| MyISAM |
+--------+
1 row in set (0.00 sec)想清除一張表的所有信息
Truncate table
Truncate table tbl_namemysql> select max(id) from insect;
+---------+
| max(id) |
+---------+
|       7 |
+---------+
1 row in set (0.00 sec)mysql> insert into insect (name, date, origin)-> values('cricket', '2006-09-11', 'basement');
Query OK, 1 row affected (0.01 sec)mysql> select last_insert_id();
+------------------+
| last_insert_id() |
+------------------+
|                9 |
+------------------+
1 row in set (0.00 sec)mysql> insert into insect (name, date, origin)-> values('month', '2006-09-14', 'windowsill');
Query OK, 1 row affected (0.01 sec)mysql> select * from insect where id = last_insert_id();
+----+-------+------------+------------+
| id | name  | date       | origin     |
+----+-------+------------+------------+
| 10 | month | 2006-09-14 | windowsill |
+----+-------+------------+------------+
1 row in set (0.00 sec)
Notepad++  insert.pl  use strict;
use warnings;
use DBI;# Connect to your database
my $dbh = DBI->connect("DBI:mysql:database=cookbook;host=localhost", "cbuser", "cbpass") or die "Could not connect to database: $DBI::errstr";# Execute your insert
$dbh->do("insert into insect (name, date, origin) values('moth', '2006-09-14','windowsill')");# Get the insert ID
my $seq = $dbh->{mysql_insertid};  # or $dbh->last_insert_id(...) depending on your driverprint "Inserted record with ID: $seq\n";# Disconnect
$dbh->disconnect;C:\Users\lenovo>perl insert.pl
Inserted record with ID: 11
C:\Users\lenovo>mysql -u cbuser -p
Enter password: ******
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 185
Server version: 8.0.40 MySQL Community Server - GPLCopyright (c) 2000, 2024, Oracle and/or its affiliates.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> use cookbook;
Database changed
mysql> select * from insect;
+----+-------------------+------------+------------+
| id | name              | date       | origin     |
+----+-------------------+------------+------------+
|  1 | housefly          | 2014-09-10 | kitchen    |
|  3 | grasshopper       | 2014-09-10 | front yard |
|  4 | stink bug         | 2014-09-10 | front yard |
|  5 | cabbage butterfly | 2014-09-10 | garden     |
|  7 | ant               | 2014-09-10 | back yard  |
|  9 | cricket           | 2006-09-11 | basement   |
| 10 | month             | 2006-09-14 | windowsill |
| 11 | moth              | 2006-09-14 | windowsill |
+----+-------------------+------------+------------+
8 rows in set (0.00 sec)
# Execute your insert  第一種方法
#$dbh->do("insert into insect (name, date, origin) values('moth', '2006-09-14','windowsill')");
替換成以下方法#第二種方法
my $sth = $dbh->prepare("insert into insect (name, date, origin) values('moth2', '2006-09-14','windowsill')");
$sth->execute();
C:\Users\lenovo>perl insert.pl
Inserted record with ID: 12
import mysql.connector
from mysql.connector import Error
from mysql.connector import constantstry:conn = mysql.connector.connect(host='localhost',database='cookbook',user='cbuser',password='cbpass',client_flags=[constants.ClientFlag.FOUND_ROWS])if conn.is_connected():print('已成功連接到數據庫')stmt = "insert into insect (name, date, origin) values('moth3', '2006-09-14', 'windowsill')"print("執行查詢:", stmt)cursor = conn.cursor()cursor.execute(stmt)print(f"查詢返回 {cursor.rowcount} 條記錄")
except Error as e:
print(f'數據庫操作錯誤: {e}')已成功連接到數據庫
執行查詢: insert into insect (name, date, origin) values('moth3', '2006-09-14', 'windowsill')
查詢返回 1 條記錄import mysql.connector
from mysql.connector import Error
from mysql.connector import constantstry:conn = mysql.connector.connect(host='localhost',database='cookbook',user='cbuser',password='cbpass',client_flags=[constants.ClientFlag.FOUND_ROWS])if conn.is_connected():print('已成功連接到數據庫')# 創建游標cursor = conn.cursor()# 執行插入操作(使用您要求的格式)cursor.execute("""insert into insect (name, date, origin)values('moth4', '2006-09-14', 'windowsill')""")# 獲取最后插入的IDlast_id = cursor.lastrowidprint(f"最后插入的記錄ID: {last_id}")# 提交事務conn.commit()print(f"影響的行數: {cursor.rowcount}")except Error as e:print(f'數據庫操作錯誤: {e}')# 發生錯誤時回滾if 'conn' in locals():conn.rollback()finally:# 關閉游標和連接if 'cursor' in locals():cursor.close()if 'conn' in locals() and conn.is_connected():conn.close()print('數據庫連接已關閉')

已成功連接到數據庫
最后插入的記錄ID: 14
影響的行數: 1
數據庫連接已關閉

mysql> select * from insect;
+----+-------------------+------------+------------+
| id | name              | date       | origin     |
+----+-------------------+------------+------------+
|  1 | housefly          | 2014-09-10 | kitchen    |
|  3 | grasshopper       | 2014-09-10 | front yard |
|  4 | stink bug         | 2014-09-10 | front yard |
|  5 | cabbage butterfly | 2014-09-10 | garden     |
|  7 | ant               | 2014-09-10 | back yard  |
|  9 | cricket           | 2006-09-11 | basement   |
| 10 | month             | 2006-09-14 | windowsill |
| 11 | moth              | 2006-09-14 | windowsill |
| 12 | moth2             | 2006-09-14 | windowsill |
| 13 | moth3             | 2006-09-14 | windowsill |
| 14 | moth4             | 2006-09-14 | windowsill |
+----+-------------------+------------+------------+
11 rows in set (0.00 sec)```sql
在這里插入代碼片

11.5 對一個已有的序列進行重新計數

mysql> alter table insect drop id;
Query OK, 11 rows affected (0.07 sec)
Records: 11  Duplicates: 0  Warnings: 0mysql> alter table insect-> add id int unsigned not null auto_increment first,-> add primary key(id);
Query OK, 11 rows affected (0.04 sec)
Records: 11  Duplicates: 0  Warnings: 0mysql> select * from insect order by id;
+----+-------------------+------------+------------+
| id | name              | date       | origin     |
+----+-------------------+------------+------------+
|  1 | housefly          | 2014-09-10 | kitchen    |
|  2 | grasshopper       | 2014-09-10 | front yard |
|  3 | stink bug         | 2014-09-10 | front yard |
|  4 | cabbage butterfly | 2014-09-10 | garden     |
|  5 | ant               | 2014-09-10 | back yard  |
|  6 | cricket           | 2006-09-11 | basement   |
|  7 | month             | 2006-09-14 | windowsill |
|  8 | moth              | 2006-09-14 | windowsill |
|  9 | moth2             | 2006-09-14 | windowsill |
| 10 | moth3             | 2006-09-14 | windowsill |
| 11 | moth4             | 2006-09-14 | windowsill |
+----+-------------------+------------+------------+
11 rows in set (0.00 sec)Mysql->alter table insert
Drop id, 
Add id int unsigned not null auto_increment first;

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/web/87057.shtml
繁體地址,請注明出處:http://hk.pswp.cn/web/87057.shtml
英文地址,請注明出處:http://en.pswp.cn/web/87057.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

Vue3 中 Excel 導出的性能優化與實戰指南

文章目錄 Vue3 中 Excel 導出的性能優化與實戰指南引言:為什么你的導出功能會卡死瀏覽器?一、前端導出方案深度剖析1.1 xlsx (SheetJS) - 輕量級冠軍1.2 exceljs - 功能強大的重量級選手 二、后端導出方案:大數據處理的救星2.1 為什么大數據需…

安卓RecyclerView實現3D滑動輪播效果全流程實戰

安卓RecyclerView實現3D滑動輪播效果全流程實戰 1. 前言 作為一名學習安卓的人,在接觸之前和之后兩種完全不同的想法: 好看和怎么實現 當初接觸到RecyclerView就覺得這個控件就可以把關于列表的所有UI實現,即便不能,也是功能十分強大 放在現在依然是應用最廣的滑動列表控…

電機控制——電機位置傳感器零位標定

在有感FOC算法中電機位置是一個重要的輸入,電機位置傳感器的作用就是測量電機的旋轉角度,通常是輸出sin(Theta)和cos(Theta)兩路模擬信號,根據這兩路模擬信號測得電機旋轉絕對角度。注意傳感器測量的是機械角度,不是電角度。 關于…

生物化學(實驗流程) PCR聚合酶鏈式反應: DNA 凝膠電泳實驗原理 實驗流程方法 實操建議筆記

凝膠電泳是分子生物學中最常用的技術之一,廣泛用于 DNA 片段的可視化、分離與識別。在獲取DNA 凝膠電泳相關設備(電泳設備 & DNA樣品染料 & 凝膠 & 染料)之后,可以考慮進行電泳操作。 整體電泳操作流程(從…

Python應用指南:利用高德地圖API獲取公交+地鐵可達圈(三)

副標題:基于模型構建器的批處理多份CSV轉換為點、線、面圖層 在地理信息系統(GIS)的實際應用中,我們經常需要處理大量以表格形式存儲的數據,例如人口統計數據、興趣點(POI)信息和監測站點記錄等…

每日算法刷題Day38 6.25:leetcode前綴和3道題,用時1h40min

5. 1749.任意子數組和的絕對值的最大值(中等,學習) 1749. 任意子數組和的絕對值的最大值 - 力扣(LeetCode) 思想 1.給你一個整數數組 nums 。一個子數組 [numsl, numsl1, ..., numsr-1, numsr] 的 和的絕對值 為 abs(numsl numsl1 ... numsr-1 nu…

創客匠人視角下創始人 IP 打造的底層邏輯與實踐路徑

在知識付費行業蓬勃發展的當下,創始人 IP 已成為連接用戶與商業價值的核心紐帶。創客匠人創始人老蔣在與行業頭部 IP 洪鑫的對話中揭示了一個關鍵命題:IP 打造的成敗,始于發心與理念的根基。從洪鑫教育中心營收超 6000 萬的案例來看&#xff…

2022/7 N2 jlpt詞匯

気力(きりょく) 清く(きよく) 記録(きろく) 記憶(きおく) 賢い(かしこい) 偉い(えらい) 凄い(すごい) 鋭い&am…

系統性能優化-8 TCP緩沖區與擁塞控制

每個 TCP 連接都有發送緩沖區和接收緩沖區,發送緩沖區存已發送未確認數據和待發送數據,接收緩沖區存接收但是沒有被上層服務讀取的數據。 # cat /proc/net/sockstat sockets: used 1885 TCP: inuse 537 orphan 0 tw 3 alloc 959 mem 10其中 mem 代表當前…

【前端】vue工程環境配置

環境準備(Windows版本) nodejs安裝 (base) PS C:\Users\Administrator> nvm install 18.8.0 (base) PS C:\Users\Administrator> nvm use 18.8.0 Now using node v18.8.0 (64-bit) (base) PS C:\Users\Administrator> npm -v 8.18.0 (base) PS C:\Users\Administrat…

什么是data version control?為什么需要它?它能解決什么問題?

Data Version Control (DVC) 是一個開源工具,專為數據科學和機器學習項目設計。它的核心目標是像 Git 管理代碼一樣來管理機器學習項目中的數據和模型文件。 簡單來說,DVC 是什么? Git for Data & Models: 它擴展了 Git 的功…

簡約計生用品商城簡介

計生用品商城簡介:uniapp結合thinkphp實現的全開源代碼, 內置基本功能:1.后臺商品excel一鍵導入 2.分銷利潤,按照利潤加個分紅

go中自動補全插件安裝-gopls

vscode中安裝gopls失敗,導致go中代碼無提示,無法自動補全引用 環境變量中設置go的代理:setx GOPROXY “https://goproxy.cn,direct”go install golang.org/x/tools/goplslatest

力扣尋找數組中心索引-性能優化思考

如下代碼 var pivotIndex function(nums) {// 空數組返回-1if (nums.length 0) return -1// 計算數組總和const totalSum nums.reduce((sum, num) > sum num, 0);let leftSum 0;// 遍歷數組查找中心索引for (let i 0; i < nums.length; i) {// 右側和 總和 - 左側…

SVN 分支管理(本文以Unity項目為例)

文章目錄 1.準備工作2.新建SVN倉庫2.拉取遠端空 trunk 到Unity項目目錄下3.設置忽略&#xff0c;提交unity項目至倉庫3.創建分支4.切換分支5.合并分支回主干&#xff08;例如將 trunk_01 合并回 trunk&#xff09;5.刪除分支&#xff08;可選&#xff09; 1.準備工作 下載Tort…

數據結構學習day6---流+讀寫函數+緩沖+定義函數

目錄 1.標準io&#xff1b; stdio.h 1.1標準io的概念 1.2Linux操作系統當中IO都是對文件的操作 1.3標準IO&#xff1a;ANSI C 設計的一組用文件IO 封裝的操作庫函數 2.文件 2.1作用 2.2linux中文件的類型 3.man 5.流: FILE* 5.1流的定義 5.2流的分類 6.c語言文…

互聯網醫院,正在發生的醫療新變革

隨著信息技術的飛速發展&#xff0c;互聯網醫院作為醫療服務的新形態&#xff0c;正在全球范圍內迅速崛起。在中國&#xff0c;這一變革尤為顯著&#xff0c;互聯網醫院不僅改善了醫療服務的可及性和便捷性&#xff0c;還極大地提升了醫療服務的質量和效率。 一、互聯網醫院的發…

rabbitmq動態創建交換機、隊列、動態綁定,銷毀

// 緩存已創建的綁定&#xff0c;避免重復聲明private final Map<String, Date> createdBindings new ConcurrentHashMap<>(); public void createAndBindQueueToExchange(String type,String clinetId, String routingKey) {String queueName routingKey;lo…

云效代碼倉庫導入自建gitlab中

登錄自建GitLab 在瀏覽器中輸入GitLab訪問地址http://192.168.1.111:81/users/sign_in&#xff0c;輸入賬號和密碼登錄GitLab服務&#xff0c;如下圖&#xff1a; 新建一個空的代碼庫 按照以下截圖順序&#xff0c;創建一個新的空項目&#xff0c;如下&#xff1a; 克隆鏡像 …

業界優秀的零信任安全管理系統產品介紹

騰訊 iOA 零信任安全管理系統 簡介&#xff1a;騰訊 iOA 零信任安全管理系統是騰訊終端安全團隊針對企業安全上云和數字化轉型&#xff0c;提供的企業網絡邊界處的應用訪問管控系統&#xff0c;為企業應用提供統一、安全、高效的訪問入口&#xff0c;同時提供終端安全加固、軟…