關閉
標題:sqlite C#
內容:
public void CREATE_MSSQL_TABLE_TO_SQLITE(string SQLiteFile, string tableName, bool isNeedFixColumn = true)
{
//判斷 SQL 裡有沒有該 table 沒有就建立一樣的
bool isNeedCreate = false;
if (!is_file(SQLiteFile))
{
isNeedCreate = true;
}
else
{
string SQL = @"
SELECT `name` FROM `sqlite_master` WHERE type='table' AND name= @tableName;
";
var PA = new Dictionary<string, string>();
PA["tableName"] = tableName;
var ra = SQLite_selectSQL_SAFE(SQLiteFile, SQL, PA);
if (ra.Rows.Count == 0)
{
isNeedCreate = true;
}
else
{
if (isNeedFixColumn)
{
SQL = "PRAGMA table_info('" + tableName + "');";
var sqlite_coumns = SQLite_selectSQL_SAFE(SQLiteFile, SQL, new Dictionary<string, string>());
List<string> sqlite_columns_lists = new List<string>();
for (int i = 0, max_i = sqlite_coumns.Rows.Count; i < max_i; i++)
{
/*
cid,name,type,notnull,dflt_value,pk
*/
sqlite_columns_lists.Add(sqlite_coumns.Rows[i]["name"].ToString());
}
//列出 MSSQL TABLE Schema ,對照 SQLite 的 table 不一樣就新增
SQL = @"
SELECT
a.TABLE_NAME ,--表格名稱
b.COLUMN_NAME ,--欄位
b.DATA_TYPE ,--資料型別
CASE WHEN b.IS_NULLABLE='YES' THEN 'Y'
WHEN b.IS_NULLABLE='NO' THEN 'N'
ELSE b.IS_NULLABLE END IS_NULLABLE,--允許空值
b.CHARACTER_MAXIMUM_LENGTH ,--最大長度
ISNULL(b.COLUMN_DEFAULT,'__NULL__') AS [COLUMN_DEFAULT] --預設值
FROM
INFORMATION_SCHEMA.TABLES a
LEFT JOIN INFORMATION_SCHEMA.COLUMNS b ON (a.TABLE_NAME=b.TABLE_NAME)
WHERE
a.TABLE_NAME=@tableName
";
var ra_columns = selectSQL_SAFE(SQL, PA); //MSSQL
//轉成物件
var ra_columns_dic = new Dictionary<string, DataRow>();
for (int i = 0, max_i = ra_columns.Rows.Count; i < max_i; i++)
{
string CNAME = ra_columns.Rows[i]["COLUMN_NAME"].ToString();
ra_columns_dic[CNAME] = ra_columns.Rows[i];
//如果 mssql 有,sqlite 沒有,就新增到 sqlite
if (!in_array(CNAME, sqlite_columns_lists))
{
//建到 sqlite
string DATA_TYPE = " text ";
DATA_TYPE = MapDataType(ra_columns_dic[CNAME]["DATA_TYPE"].ToString());
string _defaultStr = "";
if (ra_columns_dic[CNAME]["COLUMN_DEFAULT"].ToString() != "__NULL__")
{
_defaultStr = " DEFAULT '" + ra_columns_dic[CNAME]["COLUMN_DEFAULT"].ToString() + "' ";
}
//建立缺少的欄位
SQL = @"
ALTER TABLE `" + tableName + @"`
ADD '" + CNAME + @"' " + DATA_TYPE + " " + _defaultStr + @";
";
SQLite_execSQL_SAFE(SQLiteFile, SQL, new Dictionary<string, string>());
}
}
}
}
}
// SQLITE 或 Table 不存在,要新增
if (isNeedCreate)
{
//讀出 mssql 結構
string SQL = @"
SELECT t.name AS table_name, c.name AS column_name,
(SELECT DATA_TYPE FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = t.name and COLUMN_NAME = c.name ) AS [DATA_TYPE],
(SELECT IS_NULLABLE FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = t.name and COLUMN_NAME = c.name) AS [IS_NULLABLE],
(SELECT (COLUMNPROPERTY(OBJECT_ID(TABLE_SCHEMA + '.' + TABLE_NAME), COLUMN_NAME, 'IsIdentity')) FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = @TABLE_NAME AND COLUMN_NAME = c.name) AS [IsIdentity],
isnull(dc.definition,'') AS [default_value],
ep.value AS [comments]
FROM sys.tables t
INNER JOIN sys.columns c ON t.object_id = c.object_id
LEFT JOIN sys.extended_properties ep ON ep.major_id = c.object_id AND ep.minor_id = c.column_id AND ep.class = 1 AND ep.name = 'MS_Description'
LEFT JOIN sys.default_constraints dc ON c.default_object_id = dc.object_id
where t.name = @TABLE_NAME
";
var pa = new Dictionary<string, string>();
pa["TABLE_NAME"] = tableName;
var jd = selectSQL_SAFE(SQL, pa);
if (jd.Rows.Count == 0)
{
Console.WriteLine(" No such table..." + tableName);
return;
}
List<string> mssql_table_columns = new List<string>(); //取得的資料庫欄位名
for (int i = 0, max_i = jd.Rows.Count; i < max_i; i++)
{
mssql_table_columns.Add(jd.Rows[i]["column_name"].ToString());
}
//Console.WriteLine(my.json_encode(jd));
using (SQLiteConnection connection = new SQLiteConnection("Data Source=" + SQLiteFile + ";Version=3;"))
{
connection.Open();
SQL = @"
SELECT `name` FROM `sqlite_master` WHERE type='table' AND `name` = @TABLE_NAME;
";
pa.Clear();
pa["TABLE_NAME"] = tableName;
var sra = SQLite_selectSQL_SAFE(connection, SQL, pa);
if (sra.Rows.Count == 0)
{
//sqlite 沒有這筆,要建立
//""id"" integer NOT NULL PRIMARY KEY AUTOINCREMENT,
//""name"" TEXT
/*
CREATE TABLE "main"."Untitled" (
"id" integer NOT NULL PRIMARY KEY AUTOINCREMENT,
"name" TEXT NOT NULL DEFAULT '5',
"xxx" text
);
*/
SQL = @"
CREATE TABLE `" + tableName + @"` (
-- `__BY_3WA_IS_OK__` INTEGER DEFAULT '0',
";
for (int i = 0, max_i = jd.Rows.Count; i < max_i; i++)
{
string DATA_TYPE = MapDataType(jd.Rows[i]["DATA_TYPE"].ToString());
string null_string = "NOT NULL";
if (jd.Rows[i]["IS_NULLABLE"].ToString() == "YES")
{
null_string = "";
}
//default value
jd.Rows[i]["default_value"] = jd.Rows[i]["default_value"].ToString().Replace("(", "").Replace(")", "");
jd.Rows[i]["default_value"] = (jd.Rows[i]["default_value"].ToString() == "") ? "" : "'" + jd.Rows[i]["default_value"].ToString() + "'";
jd.Rows[i]["default_value"] = jd.Rows[i]["default_value"].ToString().Replace("''", "'");
jd.Rows[i]["default_value"] = (jd.Rows[i]["default_value"].ToString() == "") ? "" : "DEFAULT " + jd.Rows[i]["default_value"].ToString();
string PK = "";
if (jd.Rows[i]["IsIdentity"].ToString() == "1")
{
PK = "PRIMARY KEY AUTOINCREMENT";
}
SQL += @"`" + jd.Rows[i]["column_name"].ToString() + "` " + DATA_TYPE + " " + null_string + " " + jd.Rows[i]["default_value"].ToString() + " " + PK;
if (i != max_i - 1)
{
SQL += ",";
}
}
SQL += @"
);
";
//Console.WriteLine(SQL);
//建立
Console.WriteLine("1. 建立資料表... " + tableName);
SQLite_execSQL_SAFE(connection, SQL, new Dictionary<string, string>());
Console.WriteLine("2. SQLite 建立 INDEX... " + tableName);
//參考原MSSQL INDEX 資料,建立 SQLite INDEX
/*
CREATE INDEX "main"."INDEX,computers_id"
ON "hdd_log_copy1" (
"INDEX",
"computers_id"
);
*/
// 檢查有沒有 index
Dictionary<string, List<string>> INDEX_fields = mssql_get_table_indexs(tableName);
if (INDEX_fields != null)
{
//有 INDEX
foreach (string k in INDEX_fields.Keys)
{
SQL = @"
CREATE INDEX ""main"".""" + k + @"""
ON """ + tableName + @""" (
""" + implode("\",\"", INDEX_fields[k]) + @"""
);
";
Console.WriteLine("SQLite 建立 INDEX: " + k);
SQLite_execSQL_SAFE(connection, SQL, new Dictionary<string, string>());
}
}
//my.SQLite_execSQL_SAFE(connection, SQL, new Dictionary<string, string>());
} // if 沒表時
}; //using
}
}
public DataTable SQLite_selectSQL_SAFE(string sqliteFile, string SQL, Dictionary<string, string> m)
{
using (SQLiteConnection connection = new SQLiteConnection("Data Source=" + sqliteFile + ";Version=3;"))
{
connection.Open();
DataTable ra = SQLite_selectSQL_SAFE(connection, SQL, m);
connection.Clone();
connection.Dispose();
return ra;
}
}
public DataTable SQLite_selectSQL_SAFE(SQLiteConnection PDO, string SQL, Dictionary<string, string> m)
{
DataTable ra = new DataTable();
using (SQLiteCommand command = new SQLiteCommand(SQL, PDO))
{
// 添加参数
foreach (string n in m.Keys)
{
command.Parameters.AddWithValue("@" + n, m[n]);
}
using (SQLiteDataAdapter adapter = new SQLiteDataAdapter(command))
{
adapter.Fill(ra);
}
}
return ra;
}
public int SQLite_execSQL_SAFE(string sqliteFile, string SQL, Dictionary<string, string> m)
{
using (SQLiteConnection connection = new SQLiteConnection("Data Source=" + sqliteFile + ";Version=3;"))
{
connection.Open();
int rows = SQLite_execSQL_SAFE(connection, SQL, m);
connection.Clone();
connection.Dispose();
return rows;
}
}
public int SQLite_execSQL_SAFE(SQLiteConnection PDO, string SQL, Dictionary<string, string> m)
{
using (SQLiteCommand command = new SQLiteCommand(SQL, PDO))
{
// 添加参数
foreach (string n in m.Keys)
{
command.Parameters.AddWithValue("@" + n, m[n]);
}
return command.ExecuteNonQuery();
}
}
public Int64 SQLite_insertSQL(string sqliteFile, string table, Dictionary<string, string> m)
{
using (SQLiteConnection connection = new SQLiteConnection("Data Source=" + sqliteFile + ";Version=3;"))
{
connection.Open();
Int64 LAST_ID = SQLite_insertSQL(connection, table, m);
connection.Clone();
connection.Dispose();
return LAST_ID;
}
}
public Int64 SQLite_insertSQL(SQLiteConnection PDO, string table, Dictionary<string, string> m)
{
var pa = new ArrayList();
List<string> fields = new List<string>();
List<string> Q_fields = new List<string>();
foreach (string n in m.Keys)
{
fields.Add(n);
Q_fields.Add("@" + n);
}
string SQL = @"
INSERT INTO `" + table + @"`(`" + implode("`,`", fields) + "`)VALUES(" + implode(",", Q_fields) + @")
";
using (SQLiteCommand command = new SQLiteCommand(SQL, PDO))
{
foreach (string n in m.Keys)
{
command.Parameters.AddWithValue(n, m[n]);
}
command.ExecuteNonQuery();
command.CommandText = "SELECT last_insert_rowid()";
return Convert.ToInt64(command.ExecuteScalar());
}
}
public int SQLite_updateSQL_SAFE(string sqliteFile, string table, Dictionary<string, string> m, string whereClause, Dictionary<string, string> wpa)
{
using (SQLiteConnection connection = new SQLiteConnection("Data Source=" + sqliteFile + ";Version=3;"))
{
connection.Open();
int rows = SQLite_updateSQL_SAFE(connection, table, m, whereClause, wpa);
connection.Clone();
connection.Dispose();
return rows;
}
}
public int SQLite_updateSQL_SAFE(SQLiteConnection PDO, string table, Dictionary<string, string> m, string whereClause, Dictionary<string, string> wpa)
{
var fields = new List<string>();
var updateValues = new List<string>();
foreach (var pair in m)
{
fields.Add("`" + pair.Key + "`" + " = @" + pair.Key);
updateValues.Add(pair.Key);
}
string SQL = @"
UPDATE `" + table + @"`
SET " + string.Join(", ", fields) + @"
WHERE " + whereClause + @"
";
using (SQLiteCommand command = new SQLiteCommand(SQL, PDO))
{
foreach (var pair in m)
{
command.Parameters.AddWithValue("@" + pair.Key, pair.Value);
}
foreach (var pair in wpa)
{
command.Parameters.AddWithValue("@" + pair.Key, pair.Value);
}
return command.ExecuteNonQuery();
}
}