编程语言与数据库语句集锦

it2023-10-05  81

文章目录

MySQL常用语句集锦插入Insert去重合并Union查询Select更新UpdateIF-NULL相关函数 数据库操作自动备份表结构 编程语言C++Pythongolang 脚本windows下后台启动java程序

MySQL常用语句集锦

插入Insert

插入数据时可能要求忽略或替换掉重复数据(插入的数据上要有唯一索引或主键),此时可以:

on duplicate key update:冲突(主键或唯一索引)时,执行update语句;replace into:冲突时,先删除旧的再插入;insert ignore into:冲突时,忽略(不做任何操作); Insert Into 'Mytable'(Id, count) values(100, 1) On Duplicate Key Update count=count+1; Replace Into 'Mytable'(Id, count) values(100, 1); Insert Ignore Into 'Mytable'(Id, count) values(100, 1);

更新计数(若不存在,则插入1),并返回自己更新后的值

Insert Into counter(name, count) Values("First...", LAST_INSERT_ID(1)) ON Duplicate KEY Update count=LAST_INSERT_ID(count+1); Select LAST_INSERT_ID(); --获取真实的自己更新后的值,若不用LAST_INSERT_ID,则可能返回的是他人更新后的值

去重

查找重复的数据,并删除(以包含id, owner, mobile三列的通讯录为例;owner为所有者,mobile为好友电话)。

查找重复列(显示id大者)

Select Max(id), owner, mobile From t_friends Group By owner, mobile Where count(*)>1

删除查询到的重复列(删除id大者;必须作为子查询,再次查找一遍才可以)

DELETE FROM t_friends WHERE id in( SELECT sub.id from (Select Max(id) as id, owner, mobile From t_friends Group By owner, mobile Where count(*)>1) as sub )

合并Union

合并多个查询时,保证原查询的顺序(order by)

(SELECT * FROM t_friends WHERE id<100 ORDER BY name Limit 9999) UNION ALL (SELECT * FROM t_friends WHERE id>100 ORDER BY mobile Limit 9999)

若要保证合并后的原查询的顺序不变,则需要使用Limit语句(设定一个肯定不会超过的数量);同时为了避免合并时删除重复项,需要使用ALL(若没有ALL,则会移除重复项)。

查询Select

查找记录,判断记录是否存在:

SELECT CASE WHEN EXISTS(Select * From t_test Where Id=1) THEN 1 ELSE 0 END

查找满足条件的记录(多条组合后返回):返回最早记录的id(1,2,3)

SELECT startTime, TIMESTAMPDIFF(SECOND, UTC_TIMESTAMP(), startTim), GROUP_CONCAT(id) FROM t_test WHERE startTime=(Select MIN(startTime) From t_test) GROUP BY startTime

更新Update

修改记录,累加字段内容,更新时若有内容则连接

UPDATE t_test SET msg=CASE WHEN msg IS NULL THEN 'new-content' ELSE CONCAT_WS('; ', msg, 'new-content') END

把某列内容更新为随机内容(来源于另外一个表)

UPDATE tb_User SET randSeed = ( SELECT seed FROM tb_userTest WHERE id>=(SELECT floor(rand()*(select max(id) from tb_userTest))) LIMIT 1 ) WHERE randSeed is NULL

跨表更新数据

Update tbCall c INNER JOIN tbAccount a ON c.caller=a.caller AND c.called=a.called Set c.endTime=Now() Where a.Id=8 AND c.endTime IS NULL

IF-NULL相关函数

CREATE TABLE `tb_testOnly` ( `id` int(11) NOT NULL AUTO_INCREMENT, `name` varchar(100) DEFAULT NULL, PRIMARY KEY (`id`) ) INSERT INTO `tb_testOnly` VALUES (1, 'one'); INSERT INTO `tb_testOnly` VALUES (2, NULL);

IF(expr1,expr2,expr3),如果expr1的值为true,则返回expr2的值,如果expr1的值为false,则返回expr3的值

select if(id=1, "matched", "other"), id, name from tb_testOnly select if(name is NULL, "matched", "other"), id, name from tb_testOnly

IFNULL(expr1,expr2),如果expr1的值为null,则返回expr2的值,如果expr1的值不为null,则返回expr1的值。

select IFNULL(name,"is-null"), id, name from tb_testOnly

ISNULL(expr),如果expr的值为null,则返回1,如果expr1的值不为null,则返回0。

select ISNULL(name), id, name from tb_testOnly

NULLIF(expr1,expr2),如果expr1=expr2成立,那么返回值为null,否则返回值为expr1的值。

select NULLIF(name, "one"), id, name from tb_testOnly select NULLIF(name,NULL), id, name from tb_testOnly

数据库操作

自动备份表结构

通过mysqldump可以方便地对数据库表结构进行备份:

通过Echo命令,增加数据库创建相关语句;通过mysqldump生成表相关语句; Echo CREATE DATABASE IF NOT EXISTS db_test; > dbTest.sql Echo USE db_test; >> dbTest.sql mysqldump.exe -h 192.168.1.100 -u root -pMyPSW -d --add-drop-table >> dbTest.sql pause

编程语言

C++

字符串拆分:

std::vector<std::string> ExtSplit(const std::string &strAll, const std::string &sep, unsigned int nMax=-1){ std::vector<std::string> vec; std::string::size_type nStart=0, nCur; nCur = strAll.find(sep); while (std::string::npos != nCur){ vec.push_back(strAll.substr(nStart, nCur-nStart)); nStart = nCur+sep.length(); if(vec.size()>=nMax-1) break; nCur = strAll.find(sep, nStart); } if(nStart != strAll.length()) vec.push_back(strAll.substr(nStart)); return vec; }

移除前后缀

std::string &ExtRtrim(std::string &str, const char *ptrim = " ") { str.erase(str.find_last_not_of(ptrim) + 1); return str; } inline std::string &ExtLtrim(std::string &str, const char *ptrim = " ") { str.erase(0, str.find_first_not_of(ptrim)); return str; }

判断前后缀

bool ExtStartWith(const std::string &str, const std::string &head){ if(head.length()>str.length()) return false; return str.compare(0, head.length(), head) == 0; } bool ExtEndWith(const std::string &str, const std::string &tail){ if(tail.length()>str.length()) return false; return str.compare(str.length()-tail.length(), tail.length(), tail) == 0; }

Python

获取函数名

# sys._getframe() 得到当前栈信息FrameType,f_back得到上一级FrameType def get_funName(): print(sys._getframe().f_lineno) # 当前行数 print(sys._getframe().f_code.co_name) # 当前函数名 return sys._getframe().f_back.f_code.co_name # 调用者函数名

http请求

import requests import json def get_request(srvUrl): try: header = {"Content-Type": "application/json;charset=UTF-8"} param = {"query": "test"} # query参数 param["page"] = True # 字典中可随意增加参数 resp = requests.get(url=srvUrl, params=param, headers=header) print(resp) print(resp.json()) # 返回json格式body体 except Exception as ex: print(ex) def post_request(srvUrl): try: header = {"Content-Type": "application/json;charset=UTF-8"} body = { # JSON格式body数据 "query": "test", "page": 0, "size": 10 } resp = requests.post(url=srvUrl, headers=header, data=json.dump(body)) print(resp) print(resp.json()) # 返回json格式body体 except Exception as ex: print(ex)

golang

等待Ctrl+C信号:

// Ctrl+C fmt.Println("Print Ctrl+C to quit:") sig := make(chan os.Signal, 1) signal.Notify(sig, syscall.SIGINT, syscall.SIGTERM) fmt.Printf("quit (%V)\n", <-sig)

脚本

windows下后台启动java程序

@echo To stop MyService wmic process where "commandline like 'javaw -jar kpsoft.MyService-%%.jar' " terminate @timeout /T 3 @echo To start MyService start javaw -jar kpsoft.MyService-1.0-SNAPSHOT.jar @echo MyService started @timeout /T 2
最新回复(0)