gpt4 book ai didi

wpf - 如何在wpf中创建sqlite数据库?

转载 作者:行者123 更新时间:2023-12-04 00:40:56 24 4
gpt4 key购买 nike

我是 Windows 桌面应用程序开发的新手。请问我如何在 Windows Presentation Foundation(wpf) 中创建 SQLite 数据库?

最佳答案

你需要做两件事:

  1. 将 SQLite dll 添加到您的应用程序引用中
  2. 编写一个构建 Db 的类。

例如:

using System;
using System.Collections.Generic;
using System.Data.SQLite;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Database
{
public class DbCreator
{
SQLiteConnection dbConnection;
SQLiteCommand command;
string sqlCommand;
string dbPath = System.Environment.CurrentDirectory + "\\DB";
string dbFilePath;
public void createDbFile()
{
if (!string.IsNullOrEmpty(dbPath) && !Directory.Exists(dbPath))
Directory.CreateDirectory(dbPath);
dbFilePath = dbPath + "\\yourDb.db";
if (!System.IO.File.Exists(dbFilePath))
{
SQLiteConnection.CreateFile(dbFilePath);
}
}

public string createDbConnection()
{
string strCon = string.Format("Data Source={0};", dbFilePath);
dbConnection = new SQLiteConnection(strCon);
dbConnection.Open();
command = dbConnection.CreateCommand();
return strCon;
}

public void createTables()
{
if (!checkIfExist("MY_TABLE"))
{
sqlCommand = "CREATE TABLE MY_TBALE(idnt_test INTEGER PRIMARY KEY AUTOINCREMENT,code_test_type INTEGER";
executeQuery(sqlCommand);
}

}

public bool checkIfExist(string tableName)
{
command.CommandText = "SELECT name FROM sqlite_master WHERE name='" + tableName + "'";
var result = command.ExecuteScalar();

return result != null && result.ToString() == tableName ? true : false;
}

public void executeQuery(string sqlCommand)
{
SQLiteCommand triggerCommand = dbConnection.CreateCommand();
triggerCommand.CommandText = sqlCommand;
triggerCommand.ExecuteNonQuery();
}

public bool checkIfTableContainsData(string tableName)
{
command.CommandText = "SELECT count(*) FROM " + tableName;
var result = command.ExecuteScalar();

return Convert.ToInt32(result) > 0 ? true : false;
}


public void fillTable()
{
if (!checkIfTableContainsData("MY_TABLE"))
{
sqlCommand = "insert into MY_TABLE (code_test_type) values (999)";
executeQuery(sqlCommand);
}
}
}
}

祝你好运!

关于wpf - 如何在wpf中创建sqlite数据库?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31266217/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com