UWInfo Blog
發表新文章
[Join] | [忘記密碼] | [Login]
搜尋

搜尋意見
文章分類-#Author#
[所有文章分類]
所有文章分類
  • ASP.NET (48)
  • ASP.NET2.0 (15)
  • ASP.NET4.0 (34)
  • JavaScript (49)
  • jQuery (26)
  • FireFox (4)
  • UW系統設定 (3)
  • SQL (39)
  • SQL 2008 (25)
  • mirror (4)
  • SVN (4)
  • IE (9)
  • IIS (20)
  • IIS6 (1)
  • 閒聊 (7)
  • W3C (6)
  • 作業系統 (9)
  • C# (24)
  • CSS (12)
  • FileServer (1)
  • HTML 5 (11)
  • CKEditor (3)
  • UW.dll (13)
  • Visual Studio (16)
  • Browser (8)
  • SEO (1)
  • Google Apps (3)
  • 網站輔助系統 (4)
  • DNS (5)
  • SMTP (4)
  • 網管 (11)
  • 社群API (3)
  • SSL (4)
  • App_Inventor (1)
  • URLRewrite (2)
  • 開發工具 (6)
  • JSON (1)
  • Excel2007 (1)
  • 試題 (3)
  • LINQ (1)
  • bootstrap (0)
  • Vue (3)
  • IIS7 (3)
  • foodpanda (2)
  • 編碼 (2)
  • 資安 (3)
  • Sourcetree (1)
  • MAUI (1)
  • CMD (1)
  • my sql (1)
最新回應
  • Newtonsoft.Json.JsonConvert.DeserializeObject 失敗的情況
    test...more
  • dotnet ef dbcontext scaffold
    ...more
  • [ASP.NET] 利用 aspnet_regiis 加密 web.config
    ...more
  • IIS ARR (reverse proxy) 服務安裝
    ...more
  • [錯誤訊息] 請加入 ScriptResourceMapping 命名的 jquery (區分大小寫)
    ...more
  • 用 Javascript 跨網頁讀取 cookie (Cookie cross page, path of cookie)
    ...more
  • 線上客服 - MSN
    本人信箱被盜用以致資料外洩,是否可以請貴平台予以協助刪除該信箱之使用謝謝囉...more
  • 插入文字到游標或選取處
    aaaaa...more
  • IIS 配合 AD (Active Directory) 認証, 使用 .Net 6.0
    太感謝你了~~~你救了我被windows 認證卡了好幾天QQ...more
  • PostgreSQL 的 monitor trigger
    FOR EACH ROW 可能要改為 FOR EACH STATEMENT ...more
標籤
  • ordermain[
  • 80
  • -2755
  • 192[t]
  • html,
  • 53GELvYP
  • 遠端[t]
  • kerry
  • 老試
  • MVC
  • 光寶
  • d8yl.com
  • jq
  • 258
  • 安裝
  • pg
  • lvcfjvow
  • 版本
  • -5083
  • CSR
  • 專案
  • en21211211
  • 1552
  • fredck.fck
  • url
  • ORM
  • 5660
  • 0KeeTeam
  • 檔案分享
  • 無法新增重複的集合元
  • ad
  • 122
  • ti
  • captcha
  • irhoS4P3
  • output[t]
  • bdodo
  • mod
  • @@s2efe
  • iif
  • -9829 UNIO
  • IP
  • 9604
  • 5159
  • 刪除
  • [u2]
  • 時間
  • IDENTITY21
  • -5783
  • checked
頁數 1 / 2 下一頁
搜尋 sca 結果:
mysql 使用 EF model 要注意的地方
近日處理我們公司某個使用 my sql 的專案,已經被雷的幾次,紀錄一下

1.  使用 EF Scaffolding 指令去更新 Model ,有些欄位原本是明確型別 變成 可null型別
     也就是本來是 datetime 變成 datetime?, int 變成 int?
     看起來是一些 view 的欄位會有這些狀況,這時就要去 git revert ,避免build專案又一堆錯誤
2.  使用 IQueryable 語法處理時間要小心,不要在裡面計算時間。
     
DateTime shouldBeGiveCoinDateTime = DateTime.Now.AddDays(-14);
return dbContext.ViewOrderForCoinCronJob.AsNoTracking().Where(x =>
    x.CompletedAt <= shouldBeGiveCoinDateTime
    && x.CreatedAt >= DateTime.Now.AddYears(-1) // -> 這裡轉換mysql指令會出錯
    && x.DeletedAt == null
    && x.CoinAmount > 0
    && x.Status == (byte)ORDER_STATUS.COMPLETED
    && dbContext.PackingMain.Any(y => y.OrderId == x.Id)
    && x.IsGiveCoin != 0
    && !dbContext.CoinLog.Any(y =>
        y.OrderId == x.Id
        && y.StrKey.Contains(COIN_LOG.STRING_KEY_PREFIX.ORDER_ACCUMULATION)
    )
).ToList();

要把時間計算先算出來,再帶入式子
DateTime shouldBeGiveCoinDateTime = DateTime.Now.AddDays(-14);
DateTime createDateStartAt = DateTime.Now.AddYears(-1); // -> 先算出日期
return dbContext.ViewOrderForCoinCronJob.AsNoTracking().Where(x =>
    x.CompletedAt <= shouldBeGiveCoinDateTime
    && x.CreatedAt >= createDateStartAt // -> 帶入算好的日期
    && x.DeletedAt == null
    && x.CoinAmount > 0
    && x.Status == (byte)ORDER_STATUS.COMPLETED
    && dbContext.PackingMain.Any(y => y.OrderId == x.Id)
    && x.IsGiveCoin != 0
    && !dbContext.CoinLog.Any(y =>
        y.OrderId == x.Id
        && y.StrKey.Contains(COIN_LOG.STRING_KEY_PREFIX.ORDER_ACCUMULATION)
    )
).ToList();


 
More...
darren, 2025/3/10 下午 05:43:38
Chrome 連接藍芽 BLE 印表機(出單機),使用 ESC / POS 列印繁體中文和 Qrcode
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>BLE Printer Test</title>
    <script src="https://cdn.jsdelivr.net/npm/iconv-lite-umd@0.6.10/lib/iconv-lite-umd.js"></script>
</head>
<body>
    <h1>BLE Printer Test 123</h1>
    <button id="printTestButton">Test Print</button>
    <button id="printAgain">Print Again</button>
    <pre id="log"></pre>
    <script>
        // Function to log messages on the page
        function logMessage(message) {
            const logElement = document.getElementById('log');
            logElement.textContent += message + '\n';
        }
        var device;
        var server;
        var service;
        var characteristic;
        var name = 'T58_6752'; // 藍芽設備的名稱
        var uuid = 0x1800; //service UUID (用 BLE Scanner 找到的)
        var characteristicUuid = 0x2A00; // characteristic UUID (用 BLE Scanner 找到的)
        // Function to connect to BLE printer and send test data

        async function connectAndTestPrint() {

            try {
                logMessage("Requesting Bluetooth device...");

                // Request the BLE device
                device = await navigator.bluetooth.requestDevice({
                    //acceptAllDevices: true,
                    filters: [
                        { name: name }
                    ],
                    optionalServices: [uuid] // Replace with the correct service UUID
                });

                logMessage(`Device selected: ${device.name}`);
                logMessage(`Device uuid: ${device.id}`);

                await printAgain();


            } catch (error) {
                logMessage(`Error: ${error.message}`);
            }
        }

        // 转码方法
        function stringToGbk(str) {
            const ranges = [
                [0xA1, 0xA9, 0xA1, 0xFE],
                [0xB0, 0xF7, 0xA1, 0xFE],
                [0x81, 0xA0, 0x40, 0xFE],
                [0xAA, 0xFE, 0x40, 0xA0],
                [0xA8, 0xA9, 0x40, 0xA0],
                [0xAA, 0xAF, 0xA1, 0xFE],
                [0xF8, 0xFE, 0xA1, 0xFE],
                [0xA1, 0xA7, 0x40, 0xA0],
            ]
            const codes = new Uint16Array(23940)
            let i = 0

            for (const [b1Begin, b1End, b2Begin, b2End] of ranges) {
                for (let b2 = b2Begin; b2 <= b2End; b2++) {
                    if (b2 !== 0x7F) {
                        for (let b1 = b1Begin; b1 <= b1End; b1++) {
                            codes[i++] = b2 << 8 | b1
                        }
                    }
                }
            }
            const cstr = new TextDecoder('gbk').decode(codes)

            // 编码表
            const table = new Uint16Array(65536)
            for (let i = 0; i < cstr.length; i++) {
                table[cstr.charCodeAt(i)] = codes[i]
            }
            const buf = new Uint8Array(str.length * 2)
            let n = 0

            for (let i = 0; i < str.length; i++) {
                const code = str.charCodeAt(i)
                if (code < 0x80) {
                    buf[n++] = code
                } else {
                    const gbk = table[code]
                    buf[n++] = gbk & 0xFF
                    buf[n++] = gbk >> 8
                }
            }
            u8buf = buf.subarray(0, n)
            // console.log(u8buf);
            return u8buf
        }

        async function printAgain() {
            // Connect to the GATT server
            server = await device.gatt.connect();
            logMessage("Connected to GATT server.");

            // Get the printer service
            service = await server.getPrimaryService(uuid); // Replace with your printer's service UUID
            logMessage("Printer service retrieved.");

            // Get the characteristic for writing data
            characteristic = await service.getCharacteristic(characteristicUuid); // Replace with the correct characteristic UUID
            logMessage("Printer characteristic retrieved.");

            // Prepare test print data
            const encoder = new TextEncoder();
            const testData = encoder.encode("TEST PRINT: Hello from Web Bluetooth!\n");
            const finalData = encoder.encode("--\n--\n \n \n");

            const setFontSize = new Uint8Array([0x1D, 0x21, 0x11]); // GS ! n
            const setFontSize2 = new Uint8Array([0x1D, 0x21, 0x22]); // GS ! n
            const setFontSize3 = new Uint8Array([0x1D, 0x21, 0x33]); // GS ! n

            // Write test data to the printer
            logMessage("Sending test data to printer...");

            await characteristic.writeValue(new Uint8Array([0x1D, 0x21, 0x00]));
            await characteristic.writeValue(encoder.encode("1x1!\n"));
            await characteristic.writeValue(setFontSize);
            await characteristic.writeValue(encoder.encode("2x2!\n"));
            await characteristic.writeValue(setFontSize2);
            await characteristic.writeValue(encoder.encode("3x3!\n"));
            await characteristic.writeValue(setFontSize3);
            await characteristic.writeValue(encoder.encode("4x4!\n"));


            const initPrinter = new Uint8Array([0x1B, 0x40]); // ESC @
            await characteristic.writeValue(initPrinter);

            // 3. 設置字符集為 GBK
            const setGBK = new Uint8Array([0x1B, 0x74, 0x11]); // ESC t 0x11 (GBK)
            await characteristic.writeValue(setGBK);

            const text = "繁體中文測試\n \n";
            const encodedText = stringToGbk(text);
            await characteristic.writeValue(encodedText);
            logMessage("Test data sent successfully!");

            // QrCode 列印
            const qrData = "https://example.com"; // Your QR code data
            const qrDataLength = qrData.length + 3;
            const pL = qrDataLength & 0xFF; // Low byte
            const pH = (qrDataLength >> 8) & 0xFF; // High byte

            const commands = [
                0x1B, 0x40, // Initialize printer
                0x1D, 0x28, 0x6B, pL, pH, 0x31, 0x50, 0x30, ...new TextEncoder().encode(qrData), // Store data
                0x1D, 0x28, 0x6B, 0x03, 0x00, 0x31, 0x51, 0x30 // Print QR code
            ];

            const buffer = new Uint8Array(commands);
            await characteristic.writeValue(buffer);
            logMessage("QrCode sent successfully!");

            await characteristic.writeValue(finalData);
            logMessage("finalData sent successfully!");

            // Disconnect the GATT server
            server.disconnect();
            logMessage("Disconnected from printer.");
        }

        // Bind the function to the button
        document.getElementById('printTestButton').addEventListener('click', connectAndTestPrint);
        document.getElementById('printAgain').addEventListener('click', printAgain);
    </script>
</body>
</html>
More...
Bike, 2025/1/2 下午 02:20:15
postgreSql 大型 table 跑 Count 非常慢
可參考本文章:

https://dba.stackexchange.com/questions/245990/postgresql-extremely-slow-count-with-index-simple-query

vacuum analyze insider_event;
執行了 7 分鐘

ALTER TABLE insider_event SET (autovacuum_vacuum_scale_factor = 0, autovacuum_analyze_scale_factor = 0,  autovacuum_vacuum_threshold = 10000, autovacuum_analyze_threshold = 10000);

跑了 1.2 分鐘

修改 work_mem:
https://www.pgmustard.com/blog/work-mem

記憶體調整
https://www.enterprisedb.com/postgres-tutorials/how-tune-postgresql-memory
More...
Bike, 2024/2/5 上午 06:55:40
dotnet ef dbcontext scaffold
錯誤訊息:
dotnet : 因為找不到指定的命令或檔案,所以無法執行。
位於 線路:1 字元:1
+ dotnet ef dbcontext scaffold "Host=xxxxxxxxxxxxx;CommandTimeout=500 ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (因為找不到指定的命令或檔案,所以無法執行。:String) [], RemoteException
    + FullyQualifiedErrorId : NativeCommandError
 
可能的原因包括:
  * 內建 dotnet 命令拼寫錯誤。
  * 您預計要執行 .NET 程式,但不存在 dotnet-ef。
  * 您預計要執行全域工具,但在 PATH 上找不到此名稱且開頭為 dotnet 的可執行檔。
 
解決方法:
重新安裝套件,安裝指令:dotnet tool install --global dotnet-ef


 

參考:
dotnet ef 找不到指定的命令
 
More...
Reiko, 2023/2/13 下午 04:36:03
Visual Studio DbContext Scaffold
關於Scaffold的參數,官網雖然有文件但不是很好找,因此在此紀錄一下。
(於PM Console輸入'dotnet ef dbcontext scaffold -h'也可以查看)

-d | --data-annotations : 使用屬性定義模型
-c | --context <NAME> : 產生的DbContext名稱
--context-dir <PATH> : 產生的DbContext位置
-f | --force : 覆寫現有檔案
-o | --output-dir <PATH> : 產生的Entity Model位置
--schema <SCHEMA_NAME1>, <SCHEMA_NAME2>... : 指定Schemas產生Entity
-t | --table <TABLE_NAME1>, <TABLE_NAME2>... : 指定Table產生Entity
--use-database-names : 強制使用DB中Table與Column Name
--json : 輸出Json格式資料表於PM Console
-n | --namespace <NAMESPACE> : 指定命名空間,預設會依照專案與資料夾命名
--context-namespace <NAMESPACE> : 指定DbContext命名空間,預設會依照專案與資料夾命名
--no-onconfiguring : 不產生DbContext中的OnConfiguring
--no-pluralize : 關閉自動複數判別
-p | --project <PROJECT> : 指定專案
-s | --startup-project <PROJECT> : 指定指令執行時起始專案
--framework <FRAMEWORK> : 指定框架版本
--configuration <CONFIGURATION> : 指定配置
--no-build : 跳過專案建置
More...
梨子, 2022/12/15 下午 12:12:11
資安問題 -- Random 的替代 function
        static System.Security.Cryptography.RandomNumberGenerator RandomNumberGenerator = null;

        /// <summary>
        /// 回傳大於等於 0 小於 1
        /// </summary>
        /// <returns></returns>
        public static double NextDouble()
        {
            if (RandomNumberGenerator == null || LastRandomGenerateTime < DateTime.Now.AddMinutes(-1))
            {
                RandomNumberGenerator = System.Security.Cryptography.RandomNumberGenerator.Create();
            }

            // Generate four random bytes
            byte[] four_bytes = new byte[4];
            RandomNumberGenerator.GetBytes(four_bytes);

            // Convert the bytes to a UInt32
            uint scale = BitConverter.ToUInt32(four_bytes, 0);

            // And use that to pick a random number >= min and < max
            // 0 <= (scale / (uint.MaxValue + 1.0)) < 1
            return scale / (uint.MaxValue + 1.0);
        }

        /// <summary>
        /// 回傳值介於 min ~ (max - 1)
        /// </summary>
        /// <param name="min"></param>
        /// <param name="max"></param>
        /// <returns></returns>
        public static int GetRandomInt(int min, int max)
        {
            if(max < min)
            {
                throw new Exception("最大值不可小於最小值");
            }

            // Generate four random bytes
            byte[] four_bytes = new byte[4];
            RandomNumberGenerator.GetBytes(four_bytes);

            // And use that to pick a random number >= min and < max
            return (int)(min + (max - min) * NextDouble()); //因為 NextDouble 會小於 1,所以用無條件捨去.
        }

        /// <summary>
        /// 產生 0 ~ (max - 1) 的亂數
        /// </summary>
        /// <param name="max"></param>
        /// <returns></returns>
        public static int GetRandomInt(int max)
        {
            return GetRandomInt(0, max);
        }

        /// <summary>
        /// 產生 0 ~ (int.MaxValue - 1) 的亂數
        /// </summary>
        /// <returns></returns>
        public static int GetRandomInt()
        {
            return GetRandomInt(int.MaxValue);
        }
More...
Bike, 2022/9/22 下午 08:30:03
C# 元組與分解 (Tuple And Deconstruct)
*分解元組(Deconstructing tuples)的支援必須要至少C# 7.0以上*

以前一個funtion如果需要回傳複數個參數你會怎麼做呢?

1.可能會定義一個物件,在回傳的時候宣告並將值塞進去return。(為了一個function而去定義,好醜...)
2.又或者是將回傳參數型別直接改成dynamic,回傳時直接使用匿名物件。(performance炸裂!!!)

如果你使用了上面兩種方式...請一定!一定!!一定!!!要把這篇文章看完。

先來說說在C#7.0以前的處理方法,在呼叫function之前先將欲接收的參數宣告好並傳入。



但是這樣做有幾個缺點,
1. 當傳入的參數與傳出的參數一多起來,function定義時的參數會又臭又長。
2. 使用這個function前每次都需要宣告變數,不累嗎?
3. 不管你要不要使用這個參數,你都一定要傳入,因為ref與out不能有預設值。

接下來...讓我與各位介紹 " 元 組 元 素 "!!! (Tuple)

早上好台灣,現在我有Tuple。我很喜歡Tuple,但是速度與激情9比...咳咳...沒事。

先來個簡單的範例

定義一個funciton JohnCena

然後我們就可以很漂亮的一次性取得JohnCena的姓名、出生日期、國籍、年齡等等資料!

 
假如你的參數需要在外面先行宣告也沒問題!



而從C#10開始,甚至可以混合使用也沒關係!



這樣我們就輕鬆解決了以前的兩個缺點了,而要解決最後一個缺點更是簡單,
只需要將你想要丟棄(discard)或是用不到的那個參數使用UnderLine( _ )就可以囉!



元組元素的基礎講完了再來說說解構元素的部分
建構式想必大家都已經很熟悉了



但是'分解式'你有聽過嗎?
顧名思義就是可以定義物件被指派出去的參數!
驚不驚喜! 意不意外?

使用的方法就是在class底下新增一個Deconstruct function



如此一來我們就可以來試試看將John Cena解ㄊ一.... 分解!



建構式可以多載,分解式當然也可以!



以上就是這次的內容,有沒有覺得Coding時的可玩性又更好了呢?
不過要提醒一點,目前解構式並無法使用查看定義來移置相對應的位置,
對於可讀性會有不小的影響,但如果你想要把某個東西藏起來不讓你同事找到... (請不要這樣做!)
這次的範例也歡迎到我的GitHub參考囉!

06/09/2022   由Bike 補充
 
可以將function的回傳參數先行命名!!
直接當成物件使用,對開發效率與可讀性有著明顯的提升,相信會是未來的趨勢。

另外要道歉並修正之前將Deconstruct翻譯成解構式的錯誤
Destruct (解構式)指的是class生命周期結束前執行的function
使用方式是class名稱為dunction名稱並在前面加上波浪符號 '~'
Deconstruct的翻譯應該為分解式
More...
梨子, 2022/5/26 下午 07:58:00
MySQL效能檢測與優化 (Workbench)
首先尋找出一支欲調效的Table或Query
 
再來我們可以先使用左上方工具列 'Query' 內的 Explain Current Statement
 便可以得到如以下的連結表
 
 
由圖中可以清楚的看見每一段Query後的資料量,並發現有數張表單是呈現紅色 'Full Table Scan'
,這代表該段Query對這張表單的每一行欄位都做了掃描。
再來我們在我們的Query前方加上 'EXPLAIN' 並執行
 
便得到了該段Query所關聯的表單與其詳細資訊

其中針對EXPLAIN的欄位說明如下:
table:關連到的資料表(Table)會顯示在此。
type:顯示使用了何種類型。從最優至最差的類型為const、eq_reg、ref、range、indexhe、ALL。
possible_keys:顯示可能使用到的索引。此為從WHERE語法中選擇一個適合的欄位名稱。
key:實際使用到的索引。如果為NULL,則是沒有使用索引。
key_len:使用索引的長度。長度越短 準確性越高。
ref:顯示那一列的索引被使用。一般是一個常數(const)。
rows:MySQL用來返回資料的筆數。
Extra:MySQL用來解析額外的查詢訊息。如果此欄位的值為:Using temporary和Using filesort,表示MySQL無法使用索引。
Extra為MySQL用來解析額外的查詢訊息,其中欄位值所代表的意義如下:
Distinct:當MySQL找到相關連的資料時,就不再搜尋。
Not exists:MySQL優化 LEFT JOIN,一旦找到符合的LEFT JOIN資料後,就不再搜尋。
Range checked for each Record(index map:#):無法找到理想的索引。此為最慢的使用索引。
Using filesort:當出現這個值時,表示此SELECT語法需要優化。因為MySQL必須進行額外的步驟來進行查詢。
Using index:返回的資料是從索引中資料,而不是從實際的資料中返回,當返回的資料都出現在索引中的資料時就會發生此情況。
Using temporary:同Using filesort,表示此SELECT語法需要進行優化。此為MySQL必須建立一個暫時的資料表(Table)來儲存結果,此情況會發生在針對不同的資料進行ORDER BY,而不是GROUP BY。
Using where:使用WHERE語法中的欄位來返回結果。
System:system資料表,此為const連接類型的特殊情況。
Const:資料表中的一個記錄的最大值能夠符合這個查詢。因為只有一行,這個值就是常數,因為MySQL會先讀這個值然後把它當做常數。
eq_ref:MySQL在連接查詢時,會從最前面的資料表,對每一個記錄的聯合,從資料表中讀取一個記錄,在查詢時會使用索引為主鍵或唯一鍵的全部。
ref:只有在查詢使用了非唯一鍵或主鍵時才會發生。
range:使用索引返回一個範圍的結果。例如:使用大於>或小於<查詢時發生。
index:此為針對索引中的資料進行查詢。
ALL:針對每一筆記錄進行完全掃描,此為最壞的情況,應該盡量避免。

 
 
 
我們可以注意到 `browse_history` 這個表單在Query中並沒有使用索引,
可以從上方的QueryString中發現該段Query的Left Join是查詢`product_id`這個欄位,前往這個Table並幫其建立Index來增加檢索效率。
  
步驟三的時候可以選擇複數欄位來建立Index,但是要注意的是在使用索引欄位作為條件時,如果該索引是複合索引,那麼必須使用到該索引中的第一個欄位作為條件時才能保證系統使用該索引,否則該索引將不會被使用,並且應儘可能的讓欄位順序與索引順序相一致。

再來是在Query語句中應該注意以下事項
1.避免在索引列上進行運算, 這將導致引擎放棄使用索引而進行全表掃描。
2.不使用NOT IN和<>操作, NOT IN和<>操作都不會使用索引將進行全表掃描。NOT IN可以NOT EXISTS代替,id<>9則可使用id>9 or id<9來代替。
3.檢查where條件與order by 欄位,避免全表掃描。
4.應儘量避免在 where 子句中對欄位進行 null 值判斷,否則將導致引擎放棄使用索引而進行全表掃描,如: 可以在num上設定預設值0,確保表中num列沒有null值,然後這樣查詢: select id from t where num = 0
5.應儘量避免在 where 子句中使用 or 來連線條件,如果一個欄位有索引,一個欄位沒有索引,將導致引擎放棄使用索引而進行全表掃描。可以拆分條件,進行子句的union all查詢,如: select id from t where num=10 or name = 'admin'  拆分 select id from t where num = 10 union all select id from t where name = 'admin'
6.in 和 not in 也要慎用,否則會導致全表掃描,如: select id from t where num in(1,2,3) 對於連續的數值,能用 between 就不要用 in 了: select id from t where num between 1 and 3,
用 exists 代替 in 是一個好的選擇: select num from a where num in(select num from b) 換成 select num from a where exists(select 1 from b where num=a.num)
7.like語句的%不要前置, 否則索引失效 將導致全表掃描。
8.如果在 where 子句中使用引數,也會導致全表掃描。 因為SQL只有在執行時才會解析區域性變數,但優化程式不能將訪問計劃的選擇推遲到執行時;它必須在編譯時進行選擇。然 而,如果在編譯時建立訪問計劃,變數的值還是未知的,因而無法作為索引選擇的輸入項。
9.應儘量避免在where子句中對欄位進行函式操作,這將導致引擎放棄使用索引而進行全表掃描。
10.不要在 where 子句中的“=”左邊進行函式、算術運算或其他表示式運算,否則系統將可能無法正確使用索引。
11.在使用索引欄位作為條件時,如果該索引是複合索引,那麼必須使用到該索引中的第一個欄位作為條件時才能保證系統使用該索引,否則該索引將不會被使用,並且應儘可能的讓欄位順序與索引順序相一致。
12.Update 語句,如果只更改1、2個欄位,不要Update全部欄位,否則頻繁呼叫會引起明顯的效能消耗,同時帶來大量日誌。
對於多張大資料量(這裡幾百條就算大了)的表JOIN,要先分頁再JOIN,否則邏輯讀會很高,效能很差。
13.select count(*) from table;這樣不帶任何條件的count會引起全表掃描,並且沒有任何業務意義,是一定要杜絕的。
14.任何地方都不要使用 select * from t ,用具體的欄位列表代替“*”,不要返回用不到的任何欄位。
15.避免頻繁建立和刪除臨時表,以減少系統表資源的消耗。臨時表並不是不可使用,適當地使用它們可以使某些例程更有效,例如,當需要重複引用大型表或常用表中的某個資料集時。但是,對於一次性事件, 最好使用匯出表。
16.在新建臨時表時,如果一次性插入資料量很大,那麼可以使用 select into 代替 create table,避免造成大量 log ,以提高速度;如果資料量不大,為了緩和系統表的資源,應先create table,然後insert。
17.儘量拆分大的 DELETE 或INSERT 語句,批量提交SQL語句。
18.儘量避免使用遊標,因為遊標的效率較差,如果遊標操作的資料超過1萬行,那麼就應該考慮改寫。

參考來源:
1. http://blog.twbryce.com/mysql-explain/
2. https://www.gushiciku.cn/pl/gkis/zh-tw
3. https://www.itread01.com/content/1548581229.html
More...
梨子, 2022/3/28 下午 09:00:29
命名規則

名命規則

C#: 

    參數, 區域變數: 小駝峰(CamelCasing)
    其它: 大駝峰(PascalCasing)
    參考:
    
https://docs.microsoft.com/zh-tw/dotnet/standard/design-guidelines/naming-guidelines

Javascript:
    小駝峰(CamelCasing)


網址:
    全小寫, 用 - (減號) 分隔單字
    參考:

    https://www.seoseo.com.tw/article_detail_609.html
    https://blog.miniasp.com/post/2011/01/14/Avoid-using-underline-as-domain-name-character
    http://epaper.gotop.com.tw/pdf/acn023600.pdf


class 名命 HTML : 
    全小寫, 用 - (減號) 分隔單字 

複合字範列:
Pascal Camel Not
BitFlag bitFlag Bitflag
Callback callback CallBack
Canceled canceled Cancelled
DoNot doNot Don't
Email email EMail
Endpoint endpoint EndPoint
FileName fileName Filename
Gridline gridline GridLine
Hashtable hashtable HashTable
Id id ID
Indexes indexes Indices
LogOff logOff LogOut
LogOn logOn LogIn
Metadata metadata MetaData, metaData
Multipanel multipanel MultiPanel
Multiview multiview MultiView
Namespace namespace NameSpace
Ok ok OK
Pi pi PI
Placeholder placeholder PlaceHolder
SignIn signIn SignOn
SignOut signOut SignOff
UserName userName Username
WhiteSpace whiteSpace Whitespace
Writable writable Writeable
DateTimePicker dateTimePicker DatetimePicker
More...
Bike, 2020/7/28 上午 08:00:08
上傳圖片 直的變成橫的的問題
https://stackoverflow.com/questions/17186568/upload-from-ios-picture-to-net-app-rotate

 讀取某個參數來判斷            if (image_file.PropertyIdList.Contains(0x0112))
            {
                int rotationValue = image_file.GetPropertyItem(0x0112).Value[0];
                switch (rotationValue)
                {
                    case 1: // landscape, do nothing
                        break;

                    case 8: // rotated 90 right
                            // de-rotate:
                        image_file.RotateFlip(rotateFlipType: RotateFlipType.Rotate270FlipNone);
                        break;

                    case 3: // bottoms up
                        image_file.RotateFlip(rotateFlipType: RotateFlipType.Rotate180FlipNone);
                        break;

                    case 6: // rotated 90 left
                        image_file.RotateFlip(rotateFlipType: RotateFlipType.Rotate90FlipNone);

                        image_file.Save(Path + FileName);
                        break;
                }
            }
More...
sean, 2019/8/19 下午 06:11:28
|< 12 >|
頁數 1 / 2 下一頁
~ Uwinfo ~