I want Insert datetilme Value in SQLite with C#.But I got this runtime error. What should I do?

本小妞迷上赌 提交于 2021-02-20 03:42:07

问题


I want make Media Player with C#&VS2019

Windows Version 10

SQLite Version 3

Build Environment 32bit

I make Library Project and Console Project(Test)

But I got this runtime error.

Error System.Data.SQLite.SQLiteException 'SQL logic error near "'2021-10-30'": syntax error'

DirectoryFileManager


    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using System.IO;
    using System.Data.SQLite;
    
    namespace Eagle_Lib
    {
        public class DirectoryFileManager
        {
            private string rootPath;
            private List<FileInfo> files;
            // Singletone instance
            private static DirectoryFileManager instance = null;
    
            // Constructor
            private DirectoryFileManager()
            {
                files = new List<FileInfo>();
            }
            public static DirectoryFileManager GetInstance()
            {
                return instance == null ? instance = new DirectoryFileManager() : 
            instance;
            }
            public void Init(string rootPath)
            {
                this.rootPath = rootPath;
                // Initpath
                InitPath(rootPath);
            }
            public List<FileInfo> GetFiles()
            {
                return files;
            }
            // IsVideoFile?
            string[] videoExts = new string[]
            {
                ".mp4", ".mkv", ".avi"
            };
            private bool isVideoFile(FileInfo file)
            {
                foreach (string videoExt in videoExts)
                {
                    if (file.Extension.Equals(videoExt)) return true;
                }
                return false;
            }
            // 해당 디렉토리 내부의 모든 파일을 읽어와서 램에 올린다.
            public void InitPath(string path)
            {
                DirectoryInfo info = new DirectoryInfo(path);
    
                FileInfo[] files = info.GetFiles();
                DirectoryInfo[] dirs = info.GetDirectories();
    
                foreach (FileInfo file in files)
                {
                    if (isVideoFile(file)) this.files.Add(file);
                }
                foreach (DirectoryInfo dir in dirs)
                {
                    InitPath(dir.FullName);
                }
            }
            public void Print()
            {
                // 디버그용 Print
                foreach (FileInfo info in files)
                {
                    Console.WriteLine(info.FullName);
                }
            }
        }
    }

DBManager


    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using System.IO;
    using System.Data.SQLite;
    using System.Data;
    namespace Eagle_Lib
    {
        //DataBase
        //Table 'Files' 파일-ID 매칭 테이블
        //Name
        //uid(int pk incr)
        //filepath(text)
        //Video ID(text)
        //Stars(real) [1.0 ~ 5.0]
        //VideoPlayTime
        //Table 'Actors' Maker
        //uid (int pk incr)
        //VideoID(text)
        //ActorName(text)
        //Table "Video" 품목
        //VideoID(text pk)
        // releaseData(text) [SQLite3는 DATA Column이 없음]
        //genres(text) [text 형태의 해시태그 ]
        //Table 'Favorites' 즐겨찾기, 빠른스킵, 썸네일, 주요장면 지정
        //uid(int pk incr)
        // filepath(text)
        //start(real)
        //end(real)
        class DBManager
        {
            const string CREATE_TABLE_FILES = @"CREATE TABLE IF NOT EXISTS `Files` (
                uid INTEGER PRIMARY KEY AUTOINCREMENT,
                filepath TEXT NOT NULL,
                VideoID TEXT,
                stars REAL DEFAULT 0
            );";
            const string CREATE_TABLE_MAKERS = @"CREATE TABLE IF NOT EXISTS `Makers` (
                uid INTEGER PRIMARY KEY AUTOINCREMENT,
                VideoID TEXT,
                MakerName TEXT
            );";
            const string CREATE_TABLE_VIDEO = @"CREATE TABLE IF NOT EXISTS `Video`(
                VedioID TEXT PRIMARY KEY NOT NULL,
                releaseDate TEXT,
                genres TEXT
            );";
            const string CREATE_TABLE_FAVORITES = @"CREATE TABLE IF NOT EXISTS 
                `Favorites`(
                uid INTEGER PRIMARY KEY AUTOINCREMENT,
                filepath TEXT NOT NULL,
                start REAL,
                end REAL DEFAULT -1
            );";
            private const int DB_VERSION = 3;
            private const string dbfile = "EagleSave.db";
            private SQLiteConnection conn = null;
            private string rootPath;
            private static DBManager instance = null;
            private DBManager()
            {
    
            }
            public static DBManager GetInstance()
            {
                return instance == null ? instance = new DBManager() : instance;
            }
            public void Init(string rootPath)
            {
                this.rootPath = rootPath;
                string dbfullpath = rootPath + @"\" + dbfile;
                if (!File.Exists(dbfullpath))
                {
                    SQLiteConnection.CreateFile(dbfullpath);
                }
                conn = new SQLiteConnection("Data Source=" + dbfullpath + ";Version=" + 
                DB_VERSION);
                conn.Open();
                Execute(CREATE_TABLE_FILES);
                Execute(CREATE_TABLE_MAKERS);
                Execute(CREATE_TABLE_VIDEO);
                Execute(CREATE_TABLE_FAVORITES);
            }
            public void CleanDBAndInitialize()
            {
                if (conn == null) { Debug("DBManager : CleanDBAndInitialize 
                SQLiteConnection 
                conn is null"); return; }
                Execute("DROP TABLE IF EXISTS Files;");
                Execute("DROP TABLE IF EXISTS Makers;");
                Execute("DROP TABLE IF EXISTS Video;");
                Execute("DROP TABLE IF EXISTS Favorites;");
                Execute(CREATE_TABLE_FILES);
                Execute(CREATE_TABLE_MAKERS);
                Execute(CREATE_TABLE_VIDEO);
                Execute(CREATE_TABLE_FAVORITES);
            }
            private void Debug(string str, params object[] args)
            {
                Console.Write("[DBG:DBManager]");
                Console.WriteLine(str, args);
            }
            private void Execute(string query)
            {
                SQLiteCommand cmd = new SQLiteCommand(query, conn);
                int result = cmd.ExecuteNonQuery(); 
                Debug("Executed query: {0} Result: {1}", query, result);
            }
            private string Escape(string value)
            {
                return value;
            }
            private string Escape(object value)
            {
                return Convert.ToString(value);
            }
            private string DEscape(DateTime time)
            {
                return time.ToString(@"\'yyyy-MM-dd\'");
            }
            // INSERT && UPDATE && DELETE
            //File경로 = rootPath기준 상대경로
            //File 삽입
            public void InsertFile(string filepath)
            {
                string query = $@"INSERT INTO Files (Filepath) VALUES 
                ('{Escape(filepath)}')";
                Execute(query);
            }
            //File 제거
            public void RemoveFile(int uid)
            {
                string query = $@"DELETE FROM Files WHERE `uid`={Escape(uid)};";
                Execute(query);
            }
            //File 수정
            public void UpdateFile(int uid, string filepath, string videoID, float stars)
            {
                string query = $@"UPDATE Files SET `filepath`={Escape(filepath)}, 
                `VideoID`= 
                {Escape(videoID)}, `stars`={Escape(stars)}, `uid`={Escape(uid)}";
                Execute(query);
            }
            // File 수정2 filepath만을 이용해 ID,Stars를 편집할수 있음
            public void UpdateFile(string filepath, string videoID, float stars)
            {
                string query = $@"UPDATE Files SET `VideoID`='{Escape(videoID)}' 
                `stars`='{Escape(stars)}' WHERE `filepath`='{filepath}';";
                Execute(query);
            }
            //Maker 삽입
            public void InsertMaker(string videoID, string MakerName)
            {
                string query = $@"INSERT INTO Makers (VideoID, MakerName) VALUES 
                ('{Escape(videoID)}', '{Escape(MakerName)};";
                Execute(query);
            }
            //Maker 제거
            public void RemoveMaker(int uid)
            {
                string query = $@"DELETE FROM Maker WHERE `uid`={Escape(uid)};";
                Execute(query);
            }
            //Maker 제거2 videoID와 actorName을 이용해 제거 가능.성능이 안좋음.
            public void RemoveMaker(string videoID, string MakerName)
            {
                string query = $@"DELETE FROM Makers WHERE `VideoID`='{Escape(videoID)}' 
                 AND 
                `MakerName`='{Escape(MakerName)}'";
                Execute(query);
            }
            //Maker 수정
            public void UpdateMaker(int uid, string newName)
            {
    
                string query = $@"UPDATE Makers SET MakersName='{Escape(newName)}' WHERE 
                `uid`={Escape(uid)}";
                Execute(query);
            }
            //Video 삽입
            public void InsertVideo(string videoID, DateTime releaseDate, string[] 
                 genres)
            {
                string genreStr = "";
                foreach (string g in genres)
                {
                    genreStr = genreStr + (genreStr.Length == 0 ? g : (", " + g));
                }
                string query = $@"INSERT INTO `Video` (VideoID, releaseData, genres) 
                 VALUES 
                ({Escape(videoID)} {DEscape(releaseDate)} {Escape(genreStr)});";
                Execute(query);
            }
            //Video 제거
            public void RemoveVideo(string videoID)
            {
                string query = $@"DELETE FROM `Video` WHERE `VideoID` 
                ='{Escape(videoID)}';";
                Execute(query);
            }
            //Video 수정 
            public void UpdateVideo(string videoID, DateTime releaseDate, string[] 
                genres)
            {
                string genreStr = ""; // This is genreStr
                foreach (string g in genres)
                {
                    genreStr = genreStr + (genreStr.Length == 0 ? g : (", " + g));
                }
                string query = $@"UPDATE `Video` SET 
                 releaseDate='{DEscape(releaseDate)}', 
                `genres`='{Escape(genres)}' WHERE `VideoID`='{Escape(videoID)}';";
                Execute(query);
            }
            //Favorite 삽입
            public void InsertFavorite(string filepath, float start, float end)
            {
                string query = $@"INSERT INFO Favorite (filepath, start, 
                end)VALUES('{Escape(filepath)}', '{Escape(start)}', {Escape(end)});";
                Execute(query);
            }
            //Favorite 제거
            public void RemoveFavorite(int uid)
            {
                string query = $@"DELETE FROM Favorite WHERE `uid`='{Escape(uid)}'";
                Execute(query);
            }
            //Favorite 수정
            public void UpdateFavorite(int uid, float start, float end)
            {
                string query = $@"UPDATE Favorites SET `start`='{Escape(start)}' 
                `end`='{Escape(end)} WHERE `uid`='{Escape(uid)}';";
                Execute(query);
            }
            ///<summary>
            ///검색기능&정렬 기능
            ///1.(파일이 현재 데이터 베이스에 존재하는가)
            ///2.(ID가 현재 데이터 베이스에 존재하는가)
            ///3.Maker 검색
            ///4.Tag검색
            ///5.파일 검색
            ///6.ID검색
            ///7.즐겨찾기 검색
            ///8.별점으로 정렬
            ///</summary>
    
        }
    }

EagleSystem


    using System;
    using System.IO;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using System.Data.SQLite;
    
    namespace Eagle_Lib
    {
        public class EagleSystem
        {
            private string rootPath;
            private DBManager dbm = null;
            private DirectoryFileManager dfm = null;
            // Singletone
            private static EagleSystem instance = null;
            public static EagleSystem GetInstance()
            {
                return instance == null ? instance = new EagleSystem() : instance;
            }
            // Constructor
            private EagleSystem()
            {
                dbm = DBManager.GetInstance();
                dfm = DirectoryFileManager.GetInstance();
            }
            // Initializer
            public void Init(string rootPath)
            {
                this.rootPath = rootPath;
                // DBManager Init First
                dbm.Init(rootPath);
                // DirectoryFileManager Init Second
                dfm.Init(rootPath);
            }
    
            public void Test_DirectoryFileManager()
            {
                dfm.Print();
            }
            public void Test_DBManager_CleanUp()
            {
                dbm.CleanDBAndInitialize();
            }
            public void Test_DBManager_InsertFiles()
            {
                List<FileInfo> files = dfm.GetFiles();
                //Insert File into db Test
                foreach (FileInfo file in files)
                {
                    dbm.InsertFile(file.FullName);
                }
            }
            public void Test_DBManager_InsertVideo()
            {
                List<FileInfo> files = dfm.GetFiles();
    
                var rand = new Random();
                foreach (FileInfo file in files)
                {
                    switch (rand.Next(4))
                    {
                        case 0:
                            // videoID추가
                            dbm.InsertVideo("ABC-123", new DateTime(2021, 10, 30), new 
                            string[] { "Natural", "Sports" });
                            // 파일에 videoID 밑 별점 추가
                            dbm.UpdateFile(file.FullName, "ABC-123", 4.0f);
                            //  videoID에 Maker추가
                            dbm.InsertMaker("ABC-123", "HYES");
                            dbm.InsertMaker("ABC-123", "V-Vector3");
                            // 즐겨찾는 구간 설정
                            dbm.InsertFavorite(file.FullName, 10.0f, 20.0f);
                            dbm.InsertFavorite(file.FullName, 25.0f, 30.0f);
                            break;
                        case 1:
                            //videoID 추가
                            dbm.InsertVideo("ABD-133", new DateTime(2021, 10, 30), new 
                            string[] { "Sweat", "Powerful" });
                            // 파일에 videoID 및 별점 추가
                            dbm.UpdateFile(file.FullName, "ABD-133", 2.5f);
                            // videoID에 Maker 추가
                            dbm.InsertMaker("ABD-133", "Noddong");
                            // Maker 삭제 테스트
                            dbm.RemoveMaker("ABD-133", "Noddong");
                            // 즐겨찾는 구간 설정
                            dbm.InsertFavorite(file.FullName, 3.0f, 12.0f);
                            break;
                        case 2:
                            //videoID 추가
                            dbm.InsertVideo("MMD-412", new DateTime(2021, 10, 30), new 
                            string[] { "Horse", "Space" });
                            //파일에 videoID 및 별점 추가
                            dbm.UpdateFile(file.FullName, "MMD-412", 3.0f);
                            // videoID에 Maker추가
                            dbm.InsertMaker("MMD-412", "Genias");
                            dbm.InsertMaker("MMD-412", "ZoongZol");
                            dbm.InsertMaker("MMD-412", "Chozol");
                            ///<summary>
                            ///즐겨 찾는 구간 X
                            ///</summary>
                            break;
                        default:
                            //videoID 추가
                            dbm.InsertVideo("KWM-331", new DateTime(2021, 10, 30), new 
                           string[] { "Animal", "Human", "IT" });
                            //파일에 videoID 및 별점추가
                            dbm.UpdateFile(file.FullName, "KWM-331", 4.5f);
                            // videoID에 별점 추가
                            dbm.InsertMaker("KWM-331", "Vumjweja");
                            dbm.InsertMaker("KWM-331", "MichinNome");
                            ///<summary>
                            ///즐겨 찾는 구간 X
                            ///</summary>
                            break;
                    }
                }
            }
        }
    }

Program.cs(Console Project)


    using System;
    using System.Text;
    using System.Threading.Tasks;
    using Eagle_Lib;
    namespace Eagle_Test
    {
        /// <summary>
        /// 이 프로그램은 구현한 기능들을 테스트
        /// 하는 곳 이다
        /// Eagle 프로젝트의 기능들을 테스트 한다.
        /// </summary>
        class Program
        {
            static void TestFunction()
            {
                EagleSystem system = EagleSystem.GetInstance();
                system.Init(@"C:\VIDEOTEST");
                system.Test_DirectoryFileManager();
                system.Test_DBManager_CleanUp();
                system.Test_DBManager_InsertFiles();
                system.Test_DBManager_InsertVideo();
            }
            static void Main(string[] args)
            {
    
                TestFunction();
                Console.ReadLine(); //리드 라인
            }
        }
    }


来源:https://stackoverflow.com/questions/66181385/i-want-insert-datetilme-value-in-sqlite-with-c-but-i-got-this-runtime-error-wh

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!