繁体   English   中英

在C#中使用SQLite

[英]Using SQLite with C#

我正在尝试使用简单的SQLite数据库开发一个简单的应用程序。 我是C#的新手,所以我可能错过了一些显而易见的东西。 当我运行以下代码时,它返回错误:

SQL逻辑错误或缺少数据库。没有这样的表:客户 (编辑:是的,我已经在数据库中创建了该表,我使用sqlite命令提示符执行/确认了该表

这是我的代码:

using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SQLite;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Text;
using System.Windows.Forms;

namespace TestPersonDatabase
{
public partial class DBconnection : Form
{
    SQLiteDatabase sqliteDb = new SQLiteDatabase();

    public DBconnection()
    {
        InitializeComponent();
    }

    // Using SQLite
    private void btnInsert_Click(object sender, EventArgs e)
    {

        Dictionary<String, String> data = new Dictionary<String, String>();
        data.Add("CustomerId", this.fieldInsertId.Text);
        data.Add("FirstName", this.fieldInsertFName.Text);
        data.Add("LastName", this.fieldInsertLName.Text);
        data.Add("MobileNumber", this.fieldInsertDob.Text);

        try 
        {
            sqliteDb.Insert("Customer", data);
        }
        catch(Exception error)
        {
            MessageBox.Show(error.Message);
        }
    }
}


class SQLiteDatabase
{    String dbConnection;

public SQLiteDatabase()
{
    dbConnection = "Data Source=" + (global::TestPersonDatabase.Properties.Resources.database);
}


    public bool Insert(String tableName, Dictionary<String, String> data)
{
    String columns = "";
    String values = "";
    Boolean returnCode = true;
    foreach (KeyValuePair<String, String> val in data)
    {
        columns += String.Format(" {0},", val.Key.ToString());
        values += String.Format(" '{0}',", val.Value);
    }
    columns = columns.Substring(0, columns.Length - 1);
    values = values.Substring(0, values.Length - 1);
    try
    {
        this.ExecuteNonQuery(String.Format("insert into {0}({1}) values({2});", tableName, columns, values));
    }
    catch (Exception fail)
    {
        MessageBox.Show(fail.Message);
        returnCode = false;
    }
    return returnCode;
}

显然,上面的代码是将两个不同的类放在一起。 只是让您更容易阅读。

似乎找不到数据库文件。 但是我似乎已经正确地链接了它(在解决方案资源中)。 任何帮助将不胜感激,因为我有些困惑! 谢谢 :)

您从未打开过SQL连接,请尝试:

  dbConnection.Open();  //Initiate connection to the db

您似乎没有创建表格。

在输入任何数据之前,您需要使用以下方法创建表:

this.ExecuteNonQuerySQL("CREATE TABLE Customers(CustomerID INTEGER PRIMARY KEY, sPassword TEXT, CustomerName TEXT);");

创建表后,插入的代码应该可以正常工作。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM