111,128
社区成员
发帖
与我相关
我的任务
分享
//SQLiteHelper.cs
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using TRACE = System.Diagnostics.Debug;
using System.Data;
using System.Data.SQLite;
namespace SQLiteDemo
{
public class SQLiteHelper
{
const string _className = "SQLiteDemo.SQLiteHelper";
const string _DATA_PATH = "data source=.\\Data\\users.db";
const string _DB_DEPARTMENT_NAME = ".\\Data\\department.db";
static SQLiteConnection s_sqliteConnection;
#region << 私有 >>
static void attach(String filepath)
{
string strSQL = "ATTACH '" + filepath + "' AS " + System.IO.Path.GetFileNameWithoutExtension(filepath);
using (SQLiteCommand cmd = new SQLiteCommand(strSQL, s_sqliteConnection))
{
cmd.ExecuteNonQuery();
}
}
#endregion
#region << 公开 >>
public static bool open()
{
s_sqliteConnection = new SQLiteConnection(_DATA_PATH);
s_sqliteConnection.Open();
attach(_DB_DEPARTMENT_NAME);
return true;
}
public static bool close()
{
s_sqliteConnection.Close();
return false;
}
public static DataTable openSQL(string strSQL)
{
DataTable tableResult = new DataTable();
using (SQLiteCommand cmd = new SQLiteCommand(strSQL, s_sqliteConnection))
{
SQLiteDataReader reader = cmd.ExecuteReader();
tableResult.Load(reader);
}
return tableResult;
}
#endregion
}
}
***************************测试
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace SQLiteDemo
{
public partial class frmMain : Form
{
public frmMain()
{
InitializeComponent();
SQLiteHelper.open();
string strSQL = @"
SELECT
*
FROM
usersinfo ui LEFT JOIN
department.dep d ON ui.[id] = d.[userId] ;
";
DataTable table = SQLiteHelper.openSQL(strSQL);
foreach (DataRow row in table.Rows)
{
Console.WriteLine("userName:{0}, department:{1}", row["userName"], row["depName"]);
}
}
protected override void OnClosing(CancelEventArgs e)
{
SQLiteHelper.close();
base.OnClosing(e);
}
}
}