PriceCheaperton
PriceCheaperton

Reputation: 5349

Cannot INSERT into SQLite table using C#

My button on click looks like this:

private void button1_Click(object sender, EventArgs e)
{
    ticket.Details td = new ticket.Details();

    td.@ref = txtRef.Text;
    td.subject = txtSubject.Text;
    td.contact_name = txtContact_Name.Text;
    td.company_name = txtCompany_Name.Text;
    td.description = rtDescription.Text;
    td.business_impact = rtBusiness_Impact.Text;
    td.severity = txtSeverity.Text;

    var ticket = new ticket();

    ticket.AddTicket(td);
}

AddTicket looks like this:

public int AddTicket(Details details)
{
        const string query = "INSERT INTO support(ref, subject, contact_name, company_name, description, business_impact, severity) VALUES (@ref, @subject, @contact_name, @company_name, @description, @business_impact, @severity)";

        //here we are setting the parameter values that will be actually 
        //replaced in the query in Execute method
        var args = new Dictionary<string, object>
{
    {"@ref", details.@ref},
    {"@subject", details.subject},
    {"@contact_name", details.contact_name},
    {"@company_name", details.company_name},
    {"@description", details.description},
    {"@business_impact", details.business_impact},
    {"@severity", details.severity}
    };

    return ExecuteWrite(query, args);
}

When I look at:

return ExecuteWrite(query, args);

I can see that query is:

INSERT INTO support(ref, subject, contact_name, company_name, description, business_impact, severity) 
VALUES (@ref, @subject, @contact_name, @company_name, @description, @business_impact, @severity)

And args is 7

My ExecuteWrite looks like this:

private int ExecuteWrite(string query, Dictionary<string, object> args)
{
    int numberOfRowsAffected;

    // setup the connection to the database
    using (var con = new SQLiteConnection("Data Source=main.db"))
    {
        con.Open();

        // open a new command
        using (var cmd = new SQLiteCommand(query, con))
        {
            // set the arguments given in the query
            foreach (var pair in args)
            {
                cmd.Parameters.AddWithValue(pair.Key, pair.Value);
            }

            cmd.Prepare();

            // execute the query and get the number of row affected
            numberOfRowsAffected = cmd.ExecuteNonQuery();
        }

        return numberOfRowsAffected;
    }
}

Everything looks good, my numberOfRowsAffected is showing 1 row and my args is 7 which is correct.

I am getting no error but I just don't see any data affected in my main.db SQLite database file.

What am I doing wrong?

Upvotes: 0

Views: 163

Answers (1)

PriceCheaperton
PriceCheaperton

Reputation: 5349

The main.db was actually located in \bin\Debug as such it was working fine! Just remember if you are reading the DB using DB Browser for SQL Lite, then be sure to load the correct db!

Upvotes: 1

Related Questions