顯示具有 Sqlite 標籤的文章。 顯示所有文章
顯示具有 Sqlite 標籤的文章。 顯示所有文章

2010年3月22日 星期一

SQL 語法網站

裡面介紹了許多SQL 的 語法概念 網址如下 :

http://www.1keydata.com/tw/sql/sql.html


補充比較 複雜 的 sql 指令使用心得, 若有使用到一堆 or 及 and 的判斷的話 ,
可以使用子查詢的方式
或 用 and( xxx or xxx or xxx ...)的方式

2009年11月25日 星期三

Sqlite with C# 在資料庫新增字串

這次試者將 RSS 下載下來的資料透過 System.Data.SQLite.dll 儲存到SQLite中 , 但是 會遇到一個問題就是 文章中會包涵 單引號(') 在用 sql的 insert 指令就會有問題


目前只想到一個方法就是吧字串存成 BLOB 的方式來避免錯誤

舉例說明比較容易

假設我要輸入一組 文字 如 文章標題,內容

標題: Tuck's incoming class gives back to the Upper Valley
內容: Before the academic year officially started, the incoming class of 2011 at the Tuck School of Business at Dartmouth was busy working on consulting projects for organizations in the Upper Valley. As part of Community Outreach Day (COD), all first-year students donated half a day during orientation week to work on solving a variety of issues facing local nonprofits.

將 標題的文字存成 一個 string 叫 title
內容 的文字存成 另一個 string 叫 contant

在將string 轉成 byte array 便可以 blob 方式 存入 資料庫

/// Translation string to byte array
byte[] bTitle = Encoding.ASCII.GetBytes(title);
byte[] bContant = Encoding.ASCII.GetBytes(contant);

2009年9月16日 星期三

圖片存取 in sqlite by C# 2

之前有寫過

圖片存取 in sqlite by C#


這一篇,但那一篇的作法試從檔案中讀取圖片資料在存入sqlite的資料庫中的;

不同於那篇文章, 現在修改了一部分,能夠讀取畫面中的圖像的byte array
(在此是用C# WPF的語法)

GetImageSourceByte function 說明︰
傳入一個 ImageSource ,利用 PngBitmapEncoder 的方式將ImageSource 轉成一個 Stream 並存入 MemoryStream 中; 最後在從 MemoryStream 取得資料存到 byte array中,

參考 定義




/**
* @Name GetImageSourceByte
*
* Get the ImageSource Byte array, which can save in database as BLOB type
*
* @param EventImage [in] - image to save
* @return the image byte array
*
*/
public byte[] GetImageSourceByte(ImageSource EventImage)
{
byte[] MyData = null;

/// new a JpegBitmapEncoder and add r into it
PngBitmapEncoder e = new PngBitmapEncoder();
e.Frames.Add(EventImage as BitmapFrame);

/// new memoryStream
MemoryStream ms = new MemoryStream();

/// Save to memory
e.Save(ms);

/// Re set the position, or read the memory from the last position
///ms.Seek(0, SeekOrigin.Begin);
/// Or set position
ms.Position = 0;

MyData = new byte[ms.Length];
ms.Read(MyData, 0, System.Convert.ToInt32(ms.Length));

ms.Close();

return MyData;

}




這裡說明一下 如何取得 傳入要傳的 ImageSource
參考 定義



/// Get bound of the visual
/// g is the WPF visual object, such as "grid","canvas", "Image", ...
Rect b = VisualTreeHelper.GetDescendantBounds(g);

/// new a RenderTargetBitmap with actual size of c
RenderTargetBitmap r = new RenderTargetBitmap((int)b.Width, (int)b.Height, 96, 96, PixelFormats.Pbgra32);

/// Render visual
r.Render(g);

/// Create BitmapFrame as ImageSource
BitmapFrame BitF= BitmapFrame.Create(r);

/// Get Byte[]
byte[] Img = GetImageSourceByte(BitF);




在此感謝 James 的指點

2009年9月10日 星期四

圖片存取 in sqlite by C#

儲存圖片在資料庫中 可以將圖片轉成一種 blob type 的資料型態, 在儲存在資料庫中。

Blob 的相關用法用很多, 如以下的例子 是用 java 存取 mysql 為例
http://caterpillar.onlyfun.net/Gossip/HibernateGossip/BlobClob.html

在這裡,將使用 C# 將圖片儲存在 sqlite 上

這裡參考了 這一篇文章 http://sqlite.phxsoftware.com/forums/p/324/1329.aspx#1329

我的範例大致描述一下


此範例有使用 System.Data.SQLite; library , 如何使用 見

C sharp or .Net 使用sqlite 設定




有四個物件在視窗上

名稱 函式 說明
---------------------------------------------------------
CreateDB CreateDB_Click 建立資料庫
SaveToDB Save_Click 將圖片儲存在資料庫
LoadImageFromDB Load_Click 將圖片重資料庫讀出
imageExample null 顯示圖片的物件


顯示畫面如下



若 資料庫 及圖片以儲存 按下 LoadImageFromDB 就會重資料庫讀取檔案並顯示




CODE 如下





using System;
using System.Collections.Generic;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

using System.Data.SQLite;
using System.IO;
using System.Data;


namespace SQLiteBlobTest
{

/// Interaction logic for Window1.xaml

public partial class Window1 : Window
{

/// Set Database Root
string DataBaseRoot = Directory.GetCurrentDirectory() + "\\TestBlobDB.db";

public Window1()
{
InitializeComponent();
}



/**
* @name CreateDataBase
*
* Create Database "TestBlobDB.db",
*
*
* Must import System.Data.SQLite or it not work
* @param DataBaseRoot [in] the data base root
*
*/
public static void CreateDataBase(string DataBaseRoot)
{

/// Creat Database
SQLiteConnection.CreateFile(DataBaseRoot);

/// Open Database and set password
SQLiteConnection cnn = new SQLiteConnection("Data Source=" + DataBaseRoot);

/// Open connect
cnn.Open();

/// Close connect
cnn.Close();

}



/**
* @name CreateBlobTable
*
* Create table whcih hava two column
* Name , type is nvarchar(40) , to record the name
* Image , type is BLOB , to record the image with byte[]
*
* Must import System.Data.SQLite or not work
* @param DataBaseRoot [in] the data base root
*/
public void CreateBlobTable(string DataBaseRoot)
{

/// Open Database
SQLiteConnection cnn = new SQLiteConnection("Data Source=" + DataBaseRoot );

/// Open connect
cnn.Open();

/// Define SQLite Command object
SQLiteCommand cmd = new SQLiteCommand();
cmd.Connection = cnn;

/// Set commend to create table
cmd.CommandText = "CREATE TABLE [BlobTable] (Name nvarchar(40), Image BLOB)";

/// Execute the command, iF have exist show error message
cmd.ExecuteNonQuery();

/// Close connect
cnn.Close();
}



/**
* @name CheckDataBaseExist
*
* Check database exist or not
*
* @param DataBaseRoot [in] the data base root
* @return True if exist, otherwise false
*
*/
public Boolean CheckDataBaseExist(string DataBaseRoot)
{

/// Set return value
Boolean ExistOrNot;

/// Check file is exits
if (File.Exists(DataBaseRoot))
{
ExistOrNot = true;
}
else
{
ExistOrNot = false;
}

return ExistOrNot;
}





/**
* @name CreateDB_Click
*
* When click this button , it will create database and table
*
*
*/
private void CreateDB_Click(object sender, RoutedEventArgs e)
{

/// Set Database Root
string DataBaseRoot = this.DataBaseRoot;

/// Flag id database exist
bool FlagIsDBExist = CheckDataBaseExist(DataBaseRoot);


if (FlagIsDBExist)
{
MessageBox.Show("The Database is already exist");
}
else
{
/// Create database and table "BlobTable"
CreateDataBase(DataBaseRoot);
CreateBlobTable(DataBaseRoot);
}

}




/**
* @name Save_Click
*
* When click this button , it will save the image from cumputer to the database
*
*
*/
private void Save_Click(object sender, RoutedEventArgs e)
{


/// Set Database Root
string DataBaseRoot = this.DataBaseRoot;

/// Open Database
SQLiteConnection cnn = new SQLiteConnection("Data Source=" + DataBaseRoot);

/// Open connect
cnn.Open();

/// Define SQLite Command object
SQLiteCommand cmd = new SQLiteCommand();
cmd.Connection = cnn;



/// Open FIleStream to transform image to byte array "MyData"
/// @"C:\20090908002chiachunchuang.jpg" is your image root
FileStream fs = new FileStream(@"C:\20090908002chiachunchuang.jpg", FileMode.OpenOrCreate, FileAccess.Read);
byte[] MyData = new byte[fs.Length];
fs.Read(MyData, 0, System.Convert.ToInt32(fs.Length));
fs.Close();


/// Set commend to save the date to database
cmd.CommandText = "INSERT INTO BlobTable VALUES( 'Test', @blobdata)";
/// When using blob type using the commend to let db save blob type
cmd.Parameters.AddWithValue("@blobdata", MyData);

/// Execute the command
cmd.ExecuteNonQuery();

/// Close connect
cnn.Close();

}


/**
* @name Load_Click
*
* When click this button , it get the image from database and show on windows
*
*
*/
private void Load_Click(object sender, RoutedEventArgs e)
{

/// Declare the byte[] to record the image imformation
byte[] MyData=null;

/// Set Database Root
string DataBaseRoot = this.DataBaseRoot;

/// Open Database
SQLiteConnection cnn = new SQLiteConnection("Data Source=" + DataBaseRoot);

/// Open connect
cnn.Open();

/// Define SQLite Command object
SQLiteCommand cmd = new SQLiteCommand();
cmd.Connection = cnn;

/// Set commend to get value
cmd.CommandText = "Select * from BlobTable";

/// CommandBehavior -> using System.Data;
/// Read all information
using (SQLiteDataReader dr = cmd.ExecuteReader(CommandBehavior.CloseConnection))
{

while (dr.Read())
{
/// Get the value from db
MyData = (Byte[])dr.GetValue(1);

}
}


cnn.Close();



/// Put the image byte[] to MemoryStream
MemoryStream ms = new MemoryStream(MyData);

/// Declare BitmapImage Bi
BitmapImage Bi = new BitmapImage();

Bi.BeginInit();

/// Set Bi source from MemoryStream
Bi.StreamSource = ms;

Bi.EndInit();

/// Set the imageExample's source and it will show on windows
imageExample.Source = Bi;


}





}






}



2009年8月26日 星期三

Sqlite 檢查 table是否存在

語法如下



SELECT count(*) FROM sqlite_master WHERE type='table' and name='" + TableName+ "'";


這裡的 name 後面接的就是 table name

查詢後會顯示數目, 0表示沒有, 1 表示有, 應該不會有一樣名稱的table 所以只有 0 或 1
兩種


sqlite_master 還有其他的用法

2009年8月10日 星期一

C sharp or .Net 使用sqlite : 6(end) update data

require download System.Data.SQLite 及設定, 可見 C sharp or .Net 使用sqlite 設定

SQLiteCommand 的變數定義自行參考 SQLite.Net 的 Help

關於其他的SQL 語法,可以參考

update語法 大致如下

UPDATE table_name
SET column_name1 = value1,
column_name2 = value2, ...
[WHERE condition]
javascript:void(0)



以下是簡單的例子,將id=1 的欄位 取代乘 5



public void UpdateExampleTable(SQLiteCommand cmd)
{

try
{
/// Set drop table command
cmd.CommandText = "Update [tbl] set id=1 where id=5";
/// Execute the command, iF have not exist show error message
cmd.ExecuteNonQuery();
MessageBox.Show("update OK");
}
catch
{
MessageBox.Show("update Error");
}


}


這應該是相關的最後一篇

C sharp or .Net 使用sqlite : 5 delete data

require download System.Data.SQLite 及設定, 可見 C sharp or .Net 使用sqlite 設定

SQLiteCommand 的變數定義自行參考 SQLite.Net 的 Help

關於其他的SQL 語法,可以參考

在SQL 相關刪除的語法有3個

delete 刪除特定欄位在某個table

DELETE FROM employee WHERE id = 100;

truncate 刪除所有欄位在某個table

TRUNCATE TABLE employee;

但 SQLite 沒有 truncate 但可以用
DELETE FROM employee 的語法達成同樣效果

drop 刪除整個table


DROP TABLE employee;


以下例子,顯示相關SQLite語法

例一 刪除 table tbl 中 id =3的欄位


public void DeleteExampleTable(SQLiteCommand cmd)
{

try
{
/// Set Delete command
cmd.CommandText = "DELETE FROM [tbl] where id=3";
/// Execute the command, iF have not exist show error message
cmd.ExecuteNonQuery();
MessageBox.Show("delete OK");
}
catch
{
MessageBox.Show("delete Error");
}

}




例二 刪除 table tbl 所有的欄位達成 truncate 的效果



public void DeleteExampleTable(SQLiteCommand cmd)
{

try
{
/// Set Delete command
cmd.CommandText = "DELETE FROM [tbl]";
/// Execute the command, iF have not exist show error message
cmd.ExecuteNonQuery();
MessageBox.Show("delete OK");
}
catch
{
MessageBox.Show("delete Error");
}

}


例三 刪除 table tbl (drop)


public void DROPExampleTable(SQLiteCommand cmd)
{

try
{
/// Set drop table command
cmd.CommandText = "DROP TABLE [table]";
/// Execute the command, iF have not exist show error message
cmd.ExecuteNonQuery();
MessageBox.Show("Drop OK");
}
catch
{
MessageBox.Show("Drop Error");
}


}

C sharp or .Net 使用sqlite : 4 select data

require download System.Data.SQLite 及設定, 可見 C sharp or .Net 使用sqlite 設定

SQLiteCommand 的變數定義自行參考 SQLite.Net 的 Help


以下例子,查詢資料利用Messageshow的方式顯示查詢結果

由於此例只有兩欄,所以就只有 get 0 和 get 1




public void GetDataFromAccountTable(SQLiteCommand cmd)
{
// Set command
cmd.CommandText = "SELECT * FROM [tbl]";

/// CommandBehavior -> using System.Data;
/// Read all information
using (SQLiteDataReader dr = cmd.ExecuteReader(CommandBehavior.CloseConnection))
{
/// Read information by each record
/// GetValue(by index), the index is begin 0 to the number of Field-1
while (dr.Read())
{
MessageBox.Show("第"+ dr.GetValue(0)+" 條:" + dr.GetValue(1));
}
}




}

2009年8月6日 星期四

C sharp or .Net 使用sqlite : 3 Insert data

require download System.Data.SQLite 及設定, 可見 C sharp or .Net 使用sqlite 設定

SQLiteCommand 的變數定義自行參考 SQLite.Net 的 Help


以下例子,將資料寫入前一篇定義的table中

簡單的 Insert data function , 是利用一個for loop 一次輸入 5 筆資料
如下




public void InserDataInAccountTableTest(SQLiteCommand cmd)
{

try
{
for (int i = 0; i < 5; i++){
/// Set Commend
cmd.CommandText = string.Format("INSERT INTO [tbl] VALUES ({0}, 'Test{1}')", i,i);

/// Execute Commend

cmd.ExecuteNonQuery();
}
}
catch{ MessageBox.Show("insert Error");
}
}

C sharp or .Net 使用sqlite :2 Login DB and 新增Table

require download System.Data.SQLite 及設定, 可見 C sharp or .Net 使用sqlite 設定

SQLiteCommand 的變數定義自行參考 SQLite.Net 的 Help

簡單的 login and 新增 table function 如下




public void LoginSqliteDatabase()
{

/// Set Database Root
string DatabaseRoot = "c:\\test.db";

/// Set Database Password
string DB_Password = "password";

/// Open Database
/// Version is sqlite version
SQLiteConnection cnn = new SQLiteConnection("Data Source="+ DatabaseRoot+";"+ "Version = 3; Password ="+DB_Password);

/// Open connect
cnn.Open();


/// Define SQLite Command object
SQLiteCommand cmd = new SQLiteCommand();
cmd.Connection = cnn;

CreatExampleTable(cmd);


}


注意 login 若沒有設定密碼的話,也可以換為以下指令
SQLiteConnection cnn = new SQLiteConnection("Data Source="+ DatabaseRoot+";");




public void CreatExampleTable(SQLiteCommand cmd)
{

try
{
/// Set Creat table command
cmd.CommandText = "create table tbl(one, two)";
/// IF have exist show error message
cmd.ExecuteNonQuery();

}
catch
{
Console.WriteLine("error");
}


}


注意 creat table 指令也可以換為以下格式,定義更多資訊
cmd.CommandText = "CREATE TABLE [tbl] (int, teo nvarchar(20))";

2009年8月5日 星期三

C sharp or .Net 使用sqlite : 1 新增資料庫

步驟主要參考 守望轩-Sqlite数据库的加密

require download System.Data.SQLite 及設定, 可見 C sharp or .Net 使用sqlite 設定

SQLiteConnection的變數定義可參考

簡單的function 如下



public void CreatSqliteDatabase()
{
/// Set Database Root
string DatabaseRoot = "c:\\test.db";

/// Set Database Password
string DB_Password = "password";

/// Check file is exits
/// File.Exists() -> using System.IO;
if (File.Exists(DatabaseRoot))
{
MessageBox.Show("Already exists.");
}
else
{
/// Creat table
SQLiteConnection.CreateFile(DatabaseRoot);

/// Open Database
SQLiteConnection cnn = new SQLiteConnection("Data Source="+DatabaseRoot);

/// Open connect
cnn.Open();

/// Set default Password
cnn.ChangePassword(DB_Password);
}
}

C sharp or .Net 使用sqlite 設定

要在C# 或 .net 環境下使用Sqlite,必須安裝額外的DLL

System.Data.SQLite

SQLite.NET.0.21_x68_dll.zip

下載後,開啟專案

選擇 Project -> Add Reference 好可以 使用 他定義好得函數

使用不同的dll 有不同的 include 方法

  • System.Data.SQLite
using System.Data.SQLite
  • SQLite.NET.0.21_x68_dll.zip
using Finisar.SQLite


此外轉貼上一些例子和教學

為了說明方便,之後文章都以System.Data.SQLite 為例說明

2009年4月9日 星期四

java 執行 SQLite

下載 SQLite JDBC http://zentus.com/sqlitejdbc/
(網站上有範例code的說明介紹)
配置好路徑, (配置路徑可以見 eclipse include jar)
就可以使用了

2009年4月7日 星期二

SQLite 介紹

SQLite 是個輕小的資料庫,而且許多程式語言都有支援,此外Fire Fox 3以後的資料都是用SQLite 儲存的。

以下列出一些連結

介紹
官方網站 http://www.sqlite.org/
WIKI http://zh.wikipedia.org/wiki/SQLite
自由軟體技術支援網站 http://support.oss.org.tw/?q=node/157

教學
創造心裡的感動 http://gisanfu.pixnet.net/blog/post/7941810
研一生努力學習 http://blog.willie.tw/archives/tag/sqlite

fire fox外掛
SQLite Manager