

<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>sqlite &#8211; Max的程式語言筆記</title>
	<atom:link href="https://stackoverflow.max-everyday.com/tag/sqlite/feed/" rel="self" type="application/rss+xml" />
	<link>https://stackoverflow.max-everyday.com</link>
	<description>我要當一個豬頭，快樂過每一天</description>
	<lastBuildDate>Wed, 04 Mar 2026 12:42:32 +0000</lastBuildDate>
	<language>zh-TW</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=6.9.4</generator>

<image>
	<url>https://stackoverflow.max-everyday.com/wp-content/uploads/2017/02/max-stackoverflow-256.png</url>
	<title>sqlite &#8211; Max的程式語言筆記</title>
	<link>https://stackoverflow.max-everyday.com</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>sqlite 在 multi-threads 情況下同時寫入的問題</title>
		<link>https://stackoverflow.max-everyday.com/2026/03/sqlite-multi-threads-wal/</link>
					<comments>https://stackoverflow.max-everyday.com/2026/03/sqlite-multi-threads-wal/#respond</comments>
		
		<dc:creator><![CDATA[max-stackoverflow]]></dc:creator>
		<pubDate>Wed, 04 Mar 2026 12:42:31 +0000</pubDate>
				<category><![CDATA[Python筆記]]></category>
		<category><![CDATA[Python]]></category>
		<category><![CDATA[sqlite]]></category>
		<guid isPermaLink="false">https://stackoverflow.max-everyday.com/?p=7816</guid>

					<description><![CDATA[在多執行緒與多核心 CPU 的環境下，使用 Py...]]></description>
										<content:encoded><![CDATA[
<p>在多執行緒與多核心 CPU 的環境下，使用 Python FastAPI 搭配 SQLite 處理多人同時寫入，確實有可能遇到存取錯誤。這主要與 SQLite 的鎖定機制以及 Python 的資料庫驅動程式行為有關。</p>



<h3 class="wp-block-heading">SQLite 的鎖定機制</h3>



<p>SQLite 是一個基於檔案的資料庫，它的併發控制相對單純。當一個進程或執行緒想要寫入資料時，SQLite 會對整個資料庫檔案加上排他鎖（Exclusive Lock）。在預設的資料庫模式下，當某個連線正在寫入，其他連線的讀取或寫入請求都會被阻擋。如果寫入操作耗時過長，其他嘗試寫入的連線會因為等不到鎖而拋出 sqlite3.OperationalError: database is locked 的錯誤。</p>



<h3 class="wp-block-heading">Python 與 FastAPI 的影響</h3>



<p>FastAPI 通常運行在非同步環境下，但標準的 sqlite3 套件是同步的。如果你在 FastAPI 中使用多執行緒（例如透過 thread pool 執行同步函式），多個執行緒同時存取同一個資料庫連線會引發程式崩潰，因為 sqlite3 預設不允許跨執行緒共享連線。即使每個執行緒都有獨立連線，上述的檔案鎖問題依然存在。此外，Python 有全域解釋器鎖（GIL），雖然這在處理 I/O 密集任務時影響較小，但它確保了 Python bytecode 一次只會由一個核心執行，這並不能解決資料庫層級的競爭問題。</p>



<h3 class="wp-block-heading">如何減少存取錯誤</h3>



<p>要讓 SQLite 在多人同時寫入時更穩定，最有效的做法是開啟預寫式日誌（WAL）模式。在 WAL 模式下，讀取和寫入可以同時進行，不會互相阻塞。你可以透過執行 PRAGMA journal_mode=WAL; 來切換。另外，設定適當的 timeout 參數也很重要。在建立連線時設定 sqlite3.connect(db_file, timeout=20)，這會讓連線在遇到鎖定時先等待一段時間，而不是立即報錯。</p>



<h3 class="wp-block-heading">替代方案與考量</h3>



<p>如果你的應用場景真的有非常頻繁的併發寫入需求，SQLite 可能不是最佳選擇。雖然 WAL 模式能改善情況，但 SQLite 終究是為了單機或中輕量級應用設計的。當寫入衝突頻繁到 timeout 都無法解決時，改用像 PostgreSQL 這種客戶端伺服器架構的資料庫會是比較根本的解決辦法，因為它們能處理更細粒度的行級鎖定（Row-level locking），在多核心環境下發揮更好的效能。</p>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<p id="p-rc_fe2fd4797b23df9d-16">要在 Python 的 sqlite3 模組中啟用 WAL 模式，你需要在建立資料庫連線後執行一段 PRAGMA 指令。這個設定會儲存在資料庫檔案中，但通常建議在每次程式啟動連線時都確認一次。<sup></sup></p>



<h3 class="wp-block-heading">啟用 WAL 模式的步驟</h3>



<p id="p-rc_fe2fd4797b23df9d-17">在 Python 中，你可以透過執行 execute 方法來切換模式。這會將日誌模式從預設的 DELETE 改為 WAL。<sup></sup></p>



<pre class="wp-block-code"><code>import sqlite3

# 建立連線，建議加上 timeout 避免 busy 錯誤
conn = sqlite3.connect('example.db', timeout=10)

# 啟用 WAL 模式
conn.execute('PRAGMA journal_mode=WAL;')

# 驗證是否成功切換
cursor = conn.execute('PRAGMA journal_mode;')
print(f"目前模式為: {cursor.fetchone()&#91;0]}")

conn.close()
</code></pre>



<h3 class="wp-block-heading">為什麼要在連線時設定</h3>



<p>雖然 WAL 模式一旦設定後會持久化在資料庫標頭中，但在程式碼中明確執行這行指令有助於確保環境一致。當你啟用 WAL 後，你會發現資料庫目錄下多了兩個暫存檔（結尾為 -wal 與 -shm），這是正常現象。</p>



<h3 class="wp-block-heading">在 FastAPI 中的建議配置</h3>



<p>如果你在 FastAPI 中使用，建議在建立連線的工具函式或是 SQLAlchemy 的 engine 配置中加入這個設定。如果你使用 SQLAlchemy，可以使用 event listener 來自動執行。</p>



<pre class="wp-block-code"><code>from sqlalchemy import create_engine, event

engine = create_engine("sqlite:///./test.db")

@event.listens_for(engine, "connect")
def set_sqlite_pragma(dbapi_connection, connection_record):
    cursor = dbapi_connection.cursor()
    cursor.execute("PRAGMA journal_mode=WAL")
    cursor.execute("PRAGMA synchronous=NORMAL")
    cursor.close()
</code></pre>



<p id="p-rc_fe2fd4797b23df9d-18">這裡額外加入了 PRAGMA synchronous=NORMAL;，在 WAL 模式下配合這個設定可以大幅提升寫入速度，同時兼顧資料安全性。<sup></sup></p>



<p></p>
]]></content:encoded>
					
					<wfw:commentRss>https://stackoverflow.max-everyday.com/2026/03/sqlite-multi-threads-wal/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Windows 環境使用 XAMPP 時，遇到 SQLite3 找不到的錯誤</title>
		<link>https://stackoverflow.max-everyday.com/2026/01/windows-xampp-sqlite3/</link>
					<comments>https://stackoverflow.max-everyday.com/2026/01/windows-xampp-sqlite3/#respond</comments>
		
		<dc:creator><![CDATA[max-stackoverflow]]></dc:creator>
		<pubDate>Mon, 05 Jan 2026 08:23:28 +0000</pubDate>
				<category><![CDATA[電腦相關應用]]></category>
		<category><![CDATA[php]]></category>
		<category><![CDATA[sqlite]]></category>
		<category><![CDATA[Windows]]></category>
		<guid isPermaLink="false">https://stackoverflow.max-everyday.com/?p=7624</guid>

					<description><![CDATA[在 Windows 環境使用 XAMPP 時，遇...]]></description>
										<content:encoded><![CDATA[
<p>在 Windows 環境使用 XAMPP 時，遇到 SQLite3 找不到的錯誤，通常是因為 PHP 的擴充功能沒有開啟。這個組件在 XAMPP 預設設定中可能是關閉的，需要手動編輯設定檔。</p>



<h3 class="wp-block-heading">修改 php.ini 設定檔</h3>



<p>請先打開 XAMPP Control Panel 控制面板。點擊 Apache 該列的 Config 按鈕，選擇 php.ini 項目。</p>



<p>檔案打開後，使用搜尋功能尋找 extension=sqlite3。你會看到前面有一個分號，這代表該行被註解掉了。請刪除該行最前面的分號，修改後應該長這樣：</p>



<p>extension=sqlite3</p>



<p>接著搜尋 extension=pdo_sqlite，同樣確認前面的分號已經移除。這能確保 PDO 模式的 SQLite 也能正常運作。</p>



<h3 class="wp-block-heading">重啟 Apache 服務</h3>



<p>儲存 php.ini 檔案後回到 XAMPP 控制面板。點擊 Apache 的 Stop 按鈕停止服務。等待幾秒鐘後，再次點擊 Start 重新啟動。</p>



<p>重啟是為了讓 PHP 載入剛才修改的設定。現在重新整理網頁，錯誤應該就會消失。</p>



<h3 class="wp-block-heading">確認環境變數</h3>



<p>如果重啟後還是報錯，可能是缺少相關的 DLL 檔案。請確認 XAMPP 安裝目錄下的 php 資料夾中，是否存在 php_sqlite3.dll。</p>



<p>通常 XAMPP 都會內建這個檔案。若檔案存在卻無法讀取，請檢查 php.ini 裡的 extension_dir 是否指向正確的 ext 路徑。</p>



<p>你可以建立一個 info.php 檔案，內容寫入 phpinfo() 函式。在瀏覽器執行該檔案並搜尋 SQLite，就能確認模組是否成功掛載。</p>



<p></p>
]]></content:encoded>
					
					<wfw:commentRss>https://stackoverflow.max-everyday.com/2026/01/windows-xampp-sqlite3/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>SQLite Wasm in the browser</title>
		<link>https://stackoverflow.max-everyday.com/2023/06/sqlite-wasm-in-the-browser/</link>
					<comments>https://stackoverflow.max-everyday.com/2023/06/sqlite-wasm-in-the-browser/#respond</comments>
		
		<dc:creator><![CDATA[max-stackoverflow]]></dc:creator>
		<pubDate>Thu, 29 Jun 2023 04:15:38 +0000</pubDate>
				<category><![CDATA[javascript筆記]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[sqlite]]></category>
		<guid isPermaLink="false">https://stackoverflow.max-everyday.com/?p=4899</guid>

					<description><![CDATA[使用 sqlite wasm 的解法, 很多, ...]]></description>
										<content:encoded><![CDATA[
<p>使用 sqlite wasm 的解法, 很多, 原本我想挑戰 sql.js 的解法, 但一直無法成功, 無限的卡關. 只好使用 sqlite 官方的sqlite3.js. </p>



<p>sqlite 官方下戴點:<br><a href="https://sqlite.org/download.html">https://sqlite.org/download.html</a></p>



<p>sqlite3 WebAssembly &amp; JavaScript Documentation<br><a href="https://sqlite.org/wasm/doc/trunk/index.md">https://sqlite.org/wasm/doc/trunk/index.md</a></p>



<p>使用的範例:<br><a href="https://sqlite.org/wasm/doc/trunk/demo-123.md">https://sqlite.org/wasm/doc/trunk/demo-123.md</a></p>



<p>如果是只有要在 chrome browser 上跑的話, 是可以使用 WebSQL, This is the deprecated SQLite interface that is built into Chrome. It does not use WASM. It is coded directly in C/C++. WebSQL only runs in the main thread.  WebSQL 在少量資料與巨量資料下的反應時間都比 sqlite3 來的優異, 參考看看效能比較表:<br><a href="https://sqlite-wasm-opfs.glitch.me/speedtest.html">https://sqlite-wasm-opfs.glitch.me/speedtest.html</a></p>



<p>目前所有瀏覽器都可以用的是 Indexed Database:<br><a href="https://www.w3.org/TR/IndexedDB/">https://www.w3.org/TR/IndexedDB/</a></p>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<h2 class="wp-block-heading">IndexedDB 與 sql.js 那邊跑的較快?</h2>



<p>使用這組 keyword 問 google: <code>indexeddb sqlite wasm performance</code><br><a href="https://sqlite.org/forum/info/4a97813fcbd4f63e?t=h">https://sqlite.org/forum/info/4a97813fcbd4f63e?t=h</a></p>



<p>We did&nbsp;<em>not</em>&nbsp;benchmark against IndexedDb because, frankly, IndexedDb doesn&#8217;t really concern us. It&#8217;s a whole different beast with a whole different API, and any sort of comparisons would be apples vs. oranges. We experimented only very briefly (a single afternoon) with using IDB as backing store for an sqlite db, but we didn&#8217;t like where that was headed. That approach simply doesn&#8217;t sit well with any of us.</p>



<p>The speed of&nbsp;<em>non-persistent</em>&nbsp;I/O is essentially limited to that of the underlying JS and WASM engines. All we can really do there, in terms of influencing the speed, is compile at different optimization levels. (Compiling with -O2 consistently gives faster results than any other level.)</p>



<p>We don&#8217;t have any truly user-friendly benchmarking tools, as we just use them during testing and development, but they&#8217;re accessible at:</p>



<p><a href="https://wasm-testing.sqlite.org/">https://wasm-testing.sqlite.org/</a></p>



<p>In particular, the &#8220;speedtest1&#8221; tools are our basis for benchmarking because they&#8217;re WASM builds of the C library&#8217;s primary benchmarking tool. Using that, we can do direct comparisons against &#8220;native&#8221; (out-of-browser) speeds.</p>



<blockquote class="wp-block-quote is-layout-flow wp-block-quote-is-layout-flow">
<p>Persistence. I know that Chrome&#8217;s new APIs make file system persistence possible, but I think it&#8217;s really important that we have an IndexedDb (or equiv) fallback.</p>
</blockquote>



<p><a href="https://sqlite.org/wasm/doc/trunk/persistence.md#kvvfs"><em>cough</em>&nbsp;localStorage&nbsp;<em>cough</em>&nbsp;sessionStorage&nbsp;<em>cough</em></a></p>



<p>An IDB-based backend is not currently in the cards for this project. There&nbsp;<em>are</em>&nbsp;other projects which store sqlite in IDB:</p>



<ul class="wp-block-list">
<li><a href="https://github.com/jlongster/absurd-sql">https://github.com/jlongster/absurd-sql</a></li>



<li><a href="https://github.com/rhashimoto/wa-sqlite">https://github.com/rhashimoto/wa-sqlite</a><br>Figuring out whether/how it&#8217;s possible to import wa-sqlite&#8217;s VFSes into client-level code which uses our API is on my TODO list. That would be a huge win, as Roy has done some amazing work on providing a framework for building and testing new VFSes.</li>
</ul>



<p>This is not to be misunderstood as an official project-level stance on the topic, but i&#8217;m personally in no way keen on supporting IDB. That said, my strongly negative opinion on IDB is admittedly based mostly on the anecdotes of others, rather than personal experience, and counter-anecdotes would be dutifully considered<sup><a href="https://sqlite.org/forum/info/4a97813fcbd4f63e?t=h#footnoteC-1-a">1</a></sup>. Even so, the list of JS/WASM TODOs and want-to-dos is long enough that, even if someone were to convince us that an IDB-based implementation was worth the effort of development and supporting it forever, it&#8217;s unlikely that it would actually get done before the middle of 2023. By that time, the non-Chromium browsers will certainly (we can hope) have caught up with OPFS, making IDB a non-topic for us.</p>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<p>sqlite3 官方版本的使用範例.</p>



<h2 class="wp-block-heading">Step 1: Create the HTML</h2>



<p>loads main sqlite3.js</p>



<pre class="wp-block-code"><code>&lt;!doctype html&gt;
&lt;html lang="en-us"&gt;
  &lt;head&gt;
    &lt;meta charset="utf-8"&gt;
    &lt;meta http-equiv="Content-Type" content="text/html; charset=utf-8"&gt;
    &lt;title&gt;Hello, sqlite3&lt;/title&gt;
  &lt;/head&gt;
  &lt;body&gt;
    &lt;script src="jswasm/sqlite3.js"&gt;&lt;/script&gt;
    &lt;script src="demo-123.js"&gt;&lt;/script&gt;
  &lt;/body&gt;
&lt;/html&gt;</code></pre>



<p></p>



<h2 class="wp-block-heading">Step 2: Create a JS App</h2>



<p></p>



<pre class="wp-block-code"><code>window.sqlite3InitModule().then(function(sqlite3){
  // The module is now loaded and the sqlite3 namespace
  // object was passed to this function.
  console.log("sqlite3:", sqlite3);
});</code></pre>



<p></p>



<p>附上的測試用的範例:</p>



<pre class="wp-block-code"><code>window.sqlite3InitModule().then(function(sqlite3){
  	// The module is now loaded and the sqlite3 namespace
  	// object was passed to this function.
  	console.log("sqlite3:", sqlite3);
    sqlite3.config.warn("Installing sqlite3 bits as global S for local dev/test purposes.");
    window.S = sqlite3;
    capi = sqlite3.capi;
    wasm = sqlite3.wasm;
    console.log("sqlite3 version:",capi.sqlite3_libversion(),
        capi.sqlite3_sourceid());
    if(wasm.bigIntEnabled){
      console.log("BigInt/int64 support is enabled.");
    }else{
      console.log('warning',"BigInt/int64 support is disabled.");
    }
  
  const oo = sqlite3.oo1; /*high-level OO API*/
  let db;
  if (sqlite3.opfs) {
    db = new sqlite3.opfs.OpfsDb('/mydb.sqlite3');
    console.log('The OPFS is available.');
  } else {
    db = new oo.DB('/mydb.sqlite3', 'ct');
    console.log('The OPFS is not available.');
  }
  console.log('transient db =', db.filename);

  try {
    console.log('Create a table...');
    db.exec('CREATE TABLE IF NOT EXISTS t(a,b)');
    console.log('Insert some data using exec()...');
    let i;
    for (i = 20; i &lt;= 25; ++i) {
      db.exec({
        sql: 'INSERT INTO t(a,b) VALUES (?,?)',
        bind: &#91;i, i * 2],
      });
    }
    console.log("Query data with exec() using rowMode 'array'...");
    db.exec({
      sql: 'SELECT a FROM t ORDER BY a LIMIT 3',
      rowMode: 'array', // 'array' (default), 'object', or 'stmt'
      callback: function (row) {
        console.log('row ', ++this.counter, '=', row);
      }.bind({ counter: 0 }),
    });
  } finally {
    db.close();
  }
});</code></pre>



<p>瀏覽器 console 裡的訊息:</p>



<figure class="wp-block-image size-full"><img fetchpriority="high" decoding="async" width="1291" height="636" src="https://stackoverflow.max-everyday.com/wp-content/uploads/2023/06/2023-06-29-09_14_57-Window.jpg?v=1688012098" alt="" class="wp-image-4901" srcset="https://stackoverflow.max-everyday.com/wp-content/uploads/2023/06/2023-06-29-09_14_57-Window.jpg?v=1688012098 1291w, https://stackoverflow.max-everyday.com/wp-content/uploads/2023/06/2023-06-29-09_14_57-Window-600x296.jpg?v=1688012098 600w, https://stackoverflow.max-everyday.com/wp-content/uploads/2023/06/2023-06-29-09_14_57-Window-1024x504.jpg?v=1688012098 1024w, https://stackoverflow.max-everyday.com/wp-content/uploads/2023/06/2023-06-29-09_14_57-Window-768x378.jpg?v=1688012098 768w" sizes="(max-width: 1291px) 100vw, 1291px" /></figure>
]]></content:encoded>
					
					<wfw:commentRss>https://stackoverflow.max-everyday.com/2023/06/sqlite-wasm-in-the-browser/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>[java] Check if table exists</title>
		<link>https://stackoverflow.max-everyday.com/2017/09/java-check-if-table-exists/</link>
					<comments>https://stackoverflow.max-everyday.com/2017/09/java-check-if-table-exists/#respond</comments>
		
		<dc:creator><![CDATA[max-stackoverflow]]></dc:creator>
		<pubDate>Fri, 29 Sep 2017 03:07:28 +0000</pubDate>
				<category><![CDATA[Java筆記]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[mssql]]></category>
		<category><![CDATA[mysql]]></category>
		<category><![CDATA[sqlite]]></category>
		<guid isPermaLink="false">http://stackoverflow.max-everyday.com/?p=1424</guid>

					<description><![CDATA[之前是用 sql 去查，但會有 sql serv...]]></description>
										<content:encoded><![CDATA[<p>之前是用 sql 去查，但會有 sql server / mysql / sqlite &#8230; 等多重 server 的問題，另一個較好的解法：</p>
<p>You can use the available meta data:</p>
<pre class="lang-java prettyprint prettyprinted"><code>  <span class="typ">DatabaseMetaData</span><span class="pln"> meta </span><span class="pun">=</span><span class="pln"> con</span><span class="pun">.</span><span class="pln">getMetaData</span><span class="pun">();</span>
  <span class="typ">ResultSet</span><span class="pln"> res </span><span class="pun">=</span><span class="pln"> meta</span><span class="pun">.</span><span class="pln">getTables</span><span class="pun">(</span><span class="kwd">null</span><span class="pun">,</span> <span class="kwd">null</span><span class="pun">,</span> <span class="str">"My_Table_Name"</span><span class="pun">,</span> 
     <span class="kwd">new</span> <span class="typ">String</span><span class="pun">[]</span> <span class="pun">{</span><span class="str">"TABLE"</span><span class="pun">});</span>
  <span class="kwd">while</span> <span class="pun">(</span><span class="pln">res</span><span class="pun">.</span><span class="pln">next</span><span class="pun">())</span> <span class="pun">{</span>
     <span class="typ">System</span><span class="pun">.</span><span class="pln">out</span><span class="pun">.</span><span class="pln">println</span><span class="pun">(</span>
        <span class="str">"   "</span><span class="pun">+</span><span class="pln">res</span><span class="pun">.</span><span class="pln">getString</span><span class="pun">(</span><span class="str">"TABLE_CAT"</span><span class="pun">)</span> 
       <span class="pun">+</span> <span class="str">", "</span><span class="pun">+</span><span class="pln">res</span><span class="pun">.</span><span class="pln">getString</span><span class="pun">(</span><span class="str">"TABLE_SCHEM"</span><span class="pun">)</span>
       <span class="pun">+</span> <span class="str">", "</span><span class="pun">+</span><span class="pln">res</span><span class="pun">.</span><span class="pln">getString</span><span class="pun">(</span><span class="str">"TABLE_NAME"</span><span class="pun">)</span>
       <span class="pun">+</span> <span class="str">", "</span><span class="pun">+</span><span class="pln">res</span><span class="pun">.</span><span class="pln">getString</span><span class="pun">(</span><span class="str">"TABLE_TYPE"</span><span class="pun">)</span>
       <span class="pun">+</span> <span class="str">", "</span><span class="pun">+</span><span class="pln">res</span><span class="pun">.</span><span class="pln">getString</span><span class="pun">(</span><span class="str">"REMARKS"</span><span class="pun">));</span> 
  <span class="pun">}</span></code></pre>
<p>See <a href="http://www.herongyang.com/jdbc/JDBC-ODBC-Flat-File-List-Tables.html" rel="noreferrer">here</a> for more details. Note also the caveats in <a href="http://docs.oracle.com/javase/7/docs/api/java/sql/DatabaseMetaData.html#getTables%28java.lang.String,%20java.lang.String,%20java.lang.String,%20java.lang.String%5B%5D%29" rel="noreferrer">the JavaDoc</a>.</p>
<p>&nbsp;</p>
]]></content:encoded>
					
					<wfw:commentRss>https://stackoverflow.max-everyday.com/2017/09/java-check-if-table-exists/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Difference between 2 dates in SQLite</title>
		<link>https://stackoverflow.max-everyday.com/2017/06/difference-between-2-dates-in-sqlite/</link>
					<comments>https://stackoverflow.max-everyday.com/2017/06/difference-between-2-dates-in-sqlite/#respond</comments>
		
		<dc:creator><![CDATA[max-stackoverflow]]></dc:creator>
		<pubDate>Wed, 07 Jun 2017 14:37:30 +0000</pubDate>
				<category><![CDATA[Python筆記]]></category>
		<category><![CDATA[sqlite]]></category>
		<guid isPermaLink="false">http://stackoverflow.max-everyday.com/?p=906</guid>

					<description><![CDATA[我的需求是希望取得user 的生日後，sqlit...]]></description>
										<content:encoded><![CDATA[<p>我的需求是希望取得user 的生日後，sqlite 可以直接顯示該user 的年齡。</p>
<p>解法，先把 string 轉 python datetime:</p>
<pre>from datetime import datetime

birthday_object = datetime.strptime(birthday, '%Y-%m-%d')</pre>
<p>然後把 birthday_object 直接餵進去 sqlite 裡，</p>
<p>sqlite 的 select 用：</p>
<pre class="lang-sql prettyprint prettyprinted"><code><span class="kwd">SELECT</span><span class="pln"> julianday</span><span class="pun">(</span><span class="str">'now'</span><span class="pun">)</span> <span class="pun">-</span><span class="pln"> julianday</span><span class="pun">(</span><span class="pln">DateCreated</span><span class="pun">)</span></code>

</pre>
<p>答案就出來一半了，接下來可以用 python 處理，也可以用 sqlite, 如果是用 sqlite:</p>
<p><strong>Difference In Days</strong></p>
<pre class="lang-sql prettyprint prettyprinted"><code><span class="kwd">Select</span><span class="pln"> Cast </span><span class="pun">((</span><span class="pln">
    JulianDay</span><span class="pun">(</span><span class="pln">ToDate</span><span class="pun">)</span> <span class="pun">-</span><span class="pln"> JulianDay</span><span class="pun">(</span><span class="pln">FromDate</span><span class="pun">)</span>
<span class="pun">)</span> <span class="kwd">As</span><span class="pln"> Integer</span><span class="pun">)</span></code></pre>
<p><strong>Difference In Hours</strong></p>
<pre class="lang-sql prettyprint prettyprinted"><code><span class="kwd">Select</span><span class="pln"> Cast </span><span class="pun">((</span><span class="pln">
    JulianDay</span><span class="pun">(</span><span class="pln">ToDate</span><span class="pun">)</span> <span class="pun">-</span><span class="pln"> JulianDay</span><span class="pun">(</span><span class="pln">FromDate</span><span class="pun">)</span>
<span class="pun">)</span> <span class="pun">*</span> <span class="lit">24</span> <span class="kwd">As</span><span class="pln"> Integer</span><span class="pun">)</span></code></pre>
<p><strong>Difference In Minutes</strong></p>
<pre class="lang-sql prettyprint prettyprinted"><code><span class="kwd">Select</span><span class="pln"> Cast </span><span class="pun">((</span><span class="pln">
    JulianDay</span><span class="pun">(</span><span class="pln">ToDate</span><span class="pun">)</span> <span class="pun">-</span><span class="pln"> JulianDay</span><span class="pun">(</span><span class="pln">FromDate</span><span class="pun">)</span>
<span class="pun">)</span> <span class="pun">*</span> <span class="lit">24</span> <span class="pun">*</span> <span class="lit">60</span> <span class="kwd">As</span><span class="pln"> Integer</span><span class="pun">)</span></code></pre>
<p><strong>Difference In Seconds</strong></p>
<pre class="lang-sql prettyprint prettyprinted"><code><span class="kwd">Select</span><span class="pln"> Cast </span><span class="pun">((</span><span class="pln">
    JulianDay</span><span class="pun">(</span><span class="pln">ToDate</span><span class="pun">)</span> <span class="pun">-</span><span class="pln"> JulianDay</span><span class="pun">(</span><span class="pln">FromDate</span><span class="pun">)</span>
<span class="pun">)</span> <span class="pun">*</span> <span class="lit">24</span> <span class="pun">*</span> <span class="lit">60</span> <span class="pun">*</span> <span class="lit">60</span> <span class="kwd">As</span><span class="pln"> Integer</span><span class="pun">)</span></code></pre>
<p>&nbsp;</p>
<p>from：</p>
<p><a href="https://www.sqlite.org/lang_datefunc.html">https://www.sqlite.org/lang_datefunc.html</a></p>
]]></content:encoded>
					
					<wfw:commentRss>https://stackoverflow.max-everyday.com/2017/06/difference-between-2-dates-in-sqlite/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
	</channel>
</rss>
