dimanche 29 novembre 2015

C# SQLite insert not working

I am trying to insert some data into an SQLite file but when I try to do so nothing gets added to the file, it's the first time I deal with SQLite so not quite sure I'm doing it right. Please ask if any other information is needed.

Here is the source code.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Data.SQLite;

namespace WpfApplication1
{

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
        Readlines();
    }

    public void Readlines()
    {
        string[] lines = System.IO.File.ReadAllLines(@"D:\Projects\GFKMVC\WpfApplication1\WpfApplication1\Opgave001.txt");
        Shift shift = new Shift();

        SQLiteConnection.CreateFile("TimePlan.sqlite");

        SQLiteConnection dbcon;

        dbcon = new SQLiteConnection("Data Source=TimePlan.sqlite;Version=3;");

        dbcon.Open();

        //string DropTable = "DROP DATABASE TimePlane.sqlite";
        //SQLiteCommand dropCom = new SQLiteCommand(DropTable, dbcon);
        //dropCom.ExecuteNonQuery();

        string CreateTable = "CREATE TABLE Shifts (EmployeeID INT, Date DATETIME, StartTime DATETIME, EndTime DATETIME, Break INT)";
        SQLiteCommand createCom = new SQLiteCommand(CreateTable, dbcon);
        createCom.ExecuteNonQuery();

        foreach (string line in lines)
        {



            string[] fields = line.Split(';');

            shift.EmployeeID = Int32.Parse(fields[0]);
            DateTime dt = DateTime.ParseExact(fields[1], "yyyyMMdd", System.Globalization.CultureInfo.InvariantCulture);
            shift.Date = dt;
            DateTime st = DateTime.ParseExact(fields[2], "HHmm", System.Globalization.CultureInfo.InvariantCulture);
            shift.StartTime = st;
            DateTime et = DateTime.ParseExact(fields[3], "HHmm", System.Globalization.CultureInfo.InvariantCulture);
            shift.EndTime = et;
            shift.Break = Int32.Parse(fields[4]);

            string InsertSql = "INSERT INTO Shifts (EmployeeID, Date, StartTime, EndTime, Break) values ("+shift.EmployeeID+","+shift.EmployeeID+","+shift.StartTime+","+shift.EndTime+","+shift.Break+")";
            SQLiteCommand InsertCom = new SQLiteCommand(InsertSql, dbcon);
            InsertCom.ExecuteNonQuery();



        }

        dbcon.Close();

    }



}
}

Aucun commentaire:

Enregistrer un commentaire