1.添加引用 System.Data.SQLite.dll
2.using System.Data.SQLite;
3.原理步骤:
string path = "c:\\mydb.db";
if (!File.Exists(path)) //1.如果数据库不存在,就创建数据库
{
SQLiteConnection.CreateFile(path);
}
SQLiteConnection conn = new SQLiteConnection("Data Source="+path); //2.连接数据库
conn.Open(); //3.打开数据库
SQLiteCommand comm = conn.CreateCommand(); //4.创建命令
comm.CommandText = "SELECT count(*) FROM sqlite_master WHERE type='table' AND name='tablename'"; //5.给命令传sql语句,搜索tablename表是否存在
SQLiteDataReader reader = comm.ExecuteReader(); //6.执行命令
reader.Read(); //7.获取结果的"指针"
int num = reader.GetInt32(); //8.第一行数据的第0个值
reader.Close(); //关闭reader,如果不关闭,下面使用comm命令执行sql语句会报错
conn.Close(); //关闭连接
将txt中的数据写入到sqlite数据库中的函数。//参数file是txt文件的路径名
static void TxtToSQLite(string file)
{
string path = "c:\\mydb.db";
string sqlData = "(";
if (!File.Exists(path))
{
SQLiteConnection.CreateFile(path);
}
SQLiteConnection conn = new SQLiteConnection("Data Source=" + path);
conn.Open();
SQLiteCommand comm = conn.CreateCommand(); StreamReader sReader = new StreamReader(file);
string strLine = sReader.ReadLine(); //读取文件的第一行
string tableName = "year" + strLine.Substring(, );
//如果数据库中没有这个表就创建一个
comm.CommandText = "CREATE TABLE IF NOT EXISTS " + tableName + "(ID integer, altitude double, longitude double, p4 integer, p5 integer, p6 integer, p7 integer, p8 integer, p9 integer, p10 integer, p11 integer, p12 integer, p13 integer)";
comm.ExecuteNonQuery();
while (strLine != null)
{
while (strLine.IndexOf(" ")!=-)
{
strLine = strLine.Replace(" ", " ");
}
strLine = strLine.Replace(" ", ",");
sqlData = sqlData+strLine+"),(";
strLine = sReader.ReadLine();
}
sqlData = sqlData.Remove(sqlData.Length - , );
comm.CommandText = "INSERT INTO " + tableName + " VALUES " + sqlData ;
try
{
comm.ExecuteNonQuery();
}
catch (System.Exception ex)
{
Debug.WriteLine(ex.Message);
}
sReader.Close();
conn.Close();
}
txt数据格式:
说明:sqlite_master 、 SQLITE_TEMP_MASTER(存储临时表)
获得所有表的列表:
SELECT name FROM (SELECT * FROM sqlite_master UNION ALL SELECT * FROM sqlite_temp_master) WHERE type=’table’ ORDER BY name
下载:System.Data.SQLite.dll http://files.cnblogs.com/files/lwngreat/System.Data.SQLite.rar