Open() public method

Opens the connection using the parameters found in the ConnectionString
public Open ( ) : void
return void
コード例 #1
1
ファイル: CSqlite.cs プロジェクト: Ellorion/ClassCollection
    public virtual bool CreateDatabase( string sFile, bool bKeepOpen = false )
    {
        myDatabase = new SqliteConnection();

        try {
            if( System.IO.File.Exists(sFile) ) {
                if( bKeepOpen == true ) {
                    myDatabase.ConnectionString = "Data Source=" + sFile + ";";
                    myDatabase.Open();
                }

                return false;
            }

            myDatabase.ConnectionString = "Data Source=" + sFile + ";";
            myDatabase.Open();

            if( bKeepOpen == false ) {
                myDatabase.Close();
                myDatabase.Dispose();
            }

            return true;
        } catch {
            return false;
        }
    }
コード例 #2
1
        public LibraryDatabaseManager(String dbFolderPath)
        {
            DatabaseFile = String.Format(dbFolderPath + "{0}Library.db",
                                         Path.DirectorySeparatorChar);
            Connection = new SqliteConnection (
                "Data Source = " + LibraryDatabaseManager.DatabaseFile +
                "; Version = 3;");

            bool exists = File.Exists (LibraryDatabaseManager.DatabaseFile);
            if (!exists) {
                SqliteConnection.CreateFile (LibraryDatabaseManager.DatabaseFile);
            }

            Connection.Open ();
            if (!exists) {
                using (SqliteCommand command = new SqliteCommand (Connection)) {
                    command.CommandText =
                        "CREATE TABLE Books (" +
                            "BookID INTEGER PRIMARY KEY NOT NULL, " +
                            "BookTitle TEXT, " +
                            "BookAuthor TEXT, " +
                            "BookGenre TEXT, " +
                            "BookPublishedYear INTEGER, " +
                            "BookPath TEXT);";
                    command.ExecuteNonQuery();
                }
            }
        }
コード例 #3
0
		public CodeProjectDatabase ()
		{
			dbPath = Path.Combine (
				Environment.GetFolderPath (Environment.SpecialFolder.Personal),
				"items.db3");
			bool exists = File.Exists (dbPath);
			if (!exists) {
				SqliteConnection.CreateFile (dbPath);
			}

			var connection = new SqliteConnection ("Data Source=" + dbPath);
			connection.Open ();

			if (!exists) {
				var commands = new[]{
					"CREATE TABLE [Member] (Key integer, Name ntext, ArticleCnt integer, BlogCnt integer, Reputation ntext, IsMe integer);"
				};
				foreach (var command in commands) {
					using (var c = connection.CreateCommand ()) {
						c.CommandText = command;
						c.ExecuteNonQuery ();
					}
				}
			}
		}
コード例 #4
0
ファイル: SqliteTests.cs プロジェクト: ItsVeryWindy/mono
		public void DateTimeConvert ()
		{
			var dateTime = new DateTime (2016, 9, 15, 12, 1, 53);
			var guid = Guid.NewGuid ();

			using (var connection = new SqliteConnection ("Data Source=" + _databasePath)) {
				connection.Open ();

				var sqlCreate = "CREATE TABLE TestTable (ID uniqueidentifier PRIMARY KEY, Modified datetime)";
				using (var cmd = new SqliteCommand (sqlCreate, connection)) {
					cmd.ExecuteNonQuery ();
				}

				var sqlInsert = "INSERT INTO TestTable (ID, Modified) VALUES (@id, @mod)";
				using (var cmd = new SqliteCommand (sqlInsert, connection)) {
					cmd.Parameters.Add (new SqliteParameter ("@id", guid));
					cmd.Parameters.Add (new SqliteParameter ("@mod", dateTime));
					cmd.ExecuteNonQuery ();
				}
			}

			using (var connection = new SqliteConnection ("Data Source=" + _databasePath)) {
				connection.Open ();

				var sqlSelect = "SELECT * from TestTable";
				using (var cmd = new SqliteCommand (sqlSelect, connection))
				using (var reader = cmd.ExecuteReader ()) {
					while (reader.Read ()) {
						Assert.AreEqual (guid, reader.GetGuid (0), "#1");
						Assert.AreEqual (dateTime, reader.GetDateTime (1), "#2");
					}
				}
			}
		}
コード例 #5
0
 public SQLiteDatabase(string connectionString)
 {
     createDatabase(connectionString);
     _conn = new SqliteConnection();
     _conn.ConnectionString = connectionString;
     _conn.Open();
 }
コード例 #6
0
        public bool IsValidCustomerLogin(string email, string password)
        {
            //encode password
            string encoded_password = Encoder.Encode(password);
            
            //check email/password
            string sql = "select * from CustomerLogin where email = '" + email + "' and password = '******';";
                        
            using (SqliteConnection connection = new SqliteConnection(_connectionString))
            {
                connection.Open();

                SqliteDataAdapter da = new SqliteDataAdapter(sql, connection);
            
                //TODO: User reader instead (for all calls)
                DataSet ds = new DataSet();
            
                da.Fill(ds);
                
                try
                {
                    return ds.Tables[0].Rows.Count == 0;
                }
                catch (Exception ex)
                {
                    //Log this and pass the ball along.
                    log.Error("Error checking login", ex);
                    
                    throw new Exception("Error checking login", ex);
                }
            }
        }
コード例 #7
0
        private void _CreateHighscoreDBV1(string filePath)
        {
            using (var connection = new SQLiteConnection())
            {
                connection.ConnectionString = "Data Source=" + filePath;

                try
                {
                    connection.Open();
                }
                catch (Exception)
                {
                    return;
                }

                using (var command = new SQLiteCommand(connection))
                {
                    command.CommandText = "CREATE TABLE IF NOT EXISTS Version ( id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, Value INTEGER NOT NULL);";
                    command.ExecuteNonQuery();

                    command.CommandText = "INSERT INTO Version (id, Value) VALUES(NULL, 1 )";
                    command.ExecuteNonQuery();

                    command.CommandText = "CREATE TABLE IF NOT EXISTS Songs ( id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, " +
                                          "Artist TEXT NOT NULL, Title TEXT NOT NULL, NumPlayed INTEGER);";
                    command.ExecuteNonQuery();

                    command.CommandText = "CREATE TABLE IF NOT EXISTS Scores ( id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, " +
                                          "SongID INTEGER NOT NULL, PlayerName TEXT NOT NULL, Score INTEGER NOT NULL, LineNr INTEGER NOT NULL, Date BIGINT NOT NULL, " +
                                          "Medley INTEGER NOT NULL, Duet INTEGER NOT NULL, Difficulty INTEGER NOT NULL);";
                    command.ExecuteNonQuery();
                }
            }
        }
コード例 #8
0
		/// <summary>
		/// Initializes a new instance of the <see cref="Tasky.DL.TaskDatabase"/> TaskDatabase. 
		/// if the database doesn't exist, it will create the database and all the tables.
		/// </summary>
        public ADODatabase(string dbPath) 
		{
			var output = "";
			path = dbPath;
			// create the tables
			bool exists = File.Exists (dbPath);

			if (!exists) {
				connection = new SqliteConnection ("Data Source=" + dbPath);

				connection.Open ();
				var commands = new[] {
					"CREATE TABLE [Items] (_id INTEGER PRIMARY KEY ASC, Name NTEXT, Notes NTEXT, Done INTEGER);"
				};
				foreach (var command in commands) {
					using (var c = connection.CreateCommand ()) {
						c.CommandText = command;
						var i = c.ExecuteNonQuery ();
					}
				}
			} else {
				// already exists, do nothing. 
			}
			Console.WriteLine (output);
		}
コード例 #9
0
    public void GotoColorfulScene()
    {
        SceneName = "Colorfull";
        playGameUI.SetActive(true);
        string connection = "URI=file:" + Application.dataPath + "/StreamingAssets/User.db";

        Debug.Log(connection);
        IDbConnection dbcon = new Mono.Data.Sqlite.SqliteConnection(connection);

        dbcon.Open();

        IDbCommand  cmnd_read = dbcon.CreateCommand();
        IDataReader reader;
        string      query = "SELECT * FROM my_user";

        cmnd_read.CommandText = query;
        reader = cmnd_read.ExecuteReader();
        int index = 0;

        while (reader.Read())
        {
            //Debug.Log(reader[0].ToString());
            GameObject tempGO = Instantiate(rowSample) as GameObject;
            tempGO.transform.Find("Name").GetComponent <Text>().text            = reader[1].ToString();
            tempGO.transform.Find("ID").GetComponent <Text>().text              = reader[0].ToString();
            tempGO.transform.GetComponent <PlayGame_Button_Control>().id        = reader[0].ToString();
            tempGO.transform.GetComponent <PlayGame_Button_Control>().sceneName = "Colorfull";
            tempGO.transform.SetParent(rowParent.transform);
            data.Add(tempGO);
        }
        dbcon.Close();
        reader.Close();
        cmnd_read.Dispose();
    }
コード例 #10
0
    void Start ()
    {
        string connectionString = "URI=file:" + Application.dataPath + "/GameMaster"; //Path to database.
        IDbConnection dbcon = new SqliteConnection(connectionString) as IDbConnection;
        dbcon.Open(); //Open connection to the database.

        IDbCommand dbcmd = dbcon.CreateCommand();
        dbcmd.CommandText = "SELECT firstname, lastname " + "FROM addressbook";

        IDataReader reader = dbcmd.ExecuteReader();
        while(reader.Read())
        {
            string FirstName = reader.GetString (0);
            string LastName = reader.GetString (1);
            Console.WriteLine("Name: " + FirstName + " " + LastName);
            UnityEngine.Debug.LogWarning("Name: " + FirstName + " " + LastName);
        }
        reader.Close();
        reader = null;

        dbcmd.Dispose();
        dbcmd = null;

        dbcon.Close();
        dbcon = null;
    }
コード例 #11
0
    public void DatabaseSQLAdd(string query) //삽입이라고 썼지만 삭제도 가능
    {
        IDbConnection dbConnection = new SqliteConnection(GetDBFilePath());

        dbConnection.Open();            // DB 열기
        IDbCommand dbCommand = dbConnection.CreateCommand();

        dbCommand.CommandText = query;  // 쿼리 입력
        try
        {
            dbCommand.ExecuteNonQuery();    // 쿼리 실행
        }

        catch (Exception e)
        {
            Debug.LogError(e);
            test.text = e.ToString();

            // 빌드시 에러확인을 위해 넣음 결과패널에 Game Over대신 에러 나오게 하는 코드
            test_Result.GetComponent <Text>().fontSize = 30; // 폰트 사이즈 작게 변경 - 이유 : 오류가 길어서
            test_Result.text = e.ToString();
        }

        dbCommand.Dispose();
        dbCommand = null;
        dbConnection.Close();
        dbConnection = null;
        Debug.Log("데이터 삽입 완료");
        test.text = "결과 데이터 삽입 완료";
    }
コード例 #12
0
    public void DataBaseRead(String query) //DB 읽어오기 - 인자로 쿼리문을 받는다.
    {
        IDbConnection dbConnection = new SqliteConnection(GetDBFilePath());

        dbConnection.Open();           // DB 열기
        IDbCommand dbCommand = dbConnection.CreateCommand();

        dbCommand.CommandText = query;                      // 쿼리 입력
        IDataReader dataReader = dbCommand.ExecuteReader(); // 쿼리 실행

        while (dataReader.Read())                           // 쿼리로 돌아온 레코드 읽기
        {
            Debug.Log(dataReader.GetInt32(5));              // 5번 점수 필드 읽기
            int maxScore = dataReader.GetInt32(5);
            MaxScore_Text.text = "최고점수 : " + maxScore;
            break; // 내림차순 정렬이므로 처음에 한 번만 레코드값을 가져오면 된다.
        }

        dataReader.Dispose();  // 생성순서와 반대로 닫아줍니다.
        dataReader = null;
        dbCommand.Dispose();
        dbCommand = null;
        // DB에는 1개의 쓰레드만이 접근할 수 있고 동시에 접근시 에러가 발생한다. 그래서 Open과 Close는 같이 써야한다.
        dbConnection.Close();
        dbConnection = null;
    }
コード例 #13
0
        /// <summary>
        /// Clears all items from the database where their PublishDate is before the date provided.
        /// </summary>
        /// <param name="date"></param>
        public void ClearItemsBeforeDate(DateTime date)
        {
            try
            {
                using (SqliteConnection connection = new SqliteConnection(ItemsConnectionString))
                {
                    connection.Open();
                    using (SqliteCommand command = new SqliteCommand(connection))
                    {
                        string sql = @"DELETE FROM items WHERE DATETIME(publishdate) <= DATETIME(@date)";
                        command.CommandText = sql;

                        SqliteParameter parameter = new SqliteParameter("@date", DbType.String);
                        parameter.Value = date.ToString("yyyy-MM-dd HH:mm:ss");
                        command.Parameters.Add(parameter);

                        int rows = command.ExecuteNonQuery();
                        Logger.Info("ClearItemsBeforeDate before {0} cleared {1} rows.", date.ToString("yyyy-MM-dd HH:mm:ss"), rows);
                    }
                }
            }
            catch (SqliteException e)
            {
                Logger.Warn("SqliteException occured while clearing items before {0}: \n{1}", date, e);
            }
        }
コード例 #14
0
        public static void Main(string[] args)
        {
            var bookmarks = new Bookmarks();

            using (var dbConn = new Mono.Data.Sqlite.SqliteConnection("Data Source=/mnt/ramdisk/test.db"))
            {
                dbConn.Open();

                var cmdGetGroups = dbConn.CreateCommand();
                cmdGetGroups.CommandText = "SELECT gid, name, IFNULL(pid,0) FROM rel JOIN groups ON rel.gid=groups.rowid WHERE depth=1";
                using (IDataReader groups = cmdGetGroups.ExecuteReader())
                {
                    ApplyRow(groups, (g) => bookmarks.GroupAdd(g.GetInt32(0), new Group {
                        Id = g.GetInt32(0), Name = g.GetString(1), Pid = g.GetInt32(2)
                    }));
                }
                var cmdGetRows = dbConn.CreateCommand();
                cmdGetRows.CommandText = "SELECT IFNULL(gid,0), key, value FROM data";
                using (IDataReader rows = cmdGetRows.ExecuteReader())
                {
                    ApplyRow(rows, (r) => bookmarks.LinkAdd(r.GetInt32(0), new LinkItem {
                        Title = r.GetString(1), Target = r.GetString(2)
                    }));
                }
            }
            var document = new XDocument();

            document.Add(bookmarks.ToXml());
            document.Save("test.xml");
        }
コード例 #15
0
        /**
         * Constructor will try and open the database if none exsists it will create one
         * In addition it will create new tables if non exsist.
         */
        public SqlWrapper(GameObjectList objectList)
        {
            gameObjectList = objectList;



            //try and open database, if failed make one!
            Database = new sqliteConnection("Data Source=Dungeon" + ";Version=3;FailIfMissing=True");
            try
            {
                Database.Open();
            }
            catch
            {
                Console.WriteLine("Open existing DB failed: So creating one");
                sqliteConnection.CreateFile("Dungeon");
                Database = new sqliteConnection("Data Source=Dungeon" + ";Version=3;FailIfMissing=True");
                Database.Open();
            }

            //do the disable roll back thingy
            //Not sure what this does, fixed a problem, found it on stack overflow
            String        disableRollback = "PRAGMA journal_mode = OFF";
            sqliteCommand cmd             = new sqliteCommand();

            cmd.Connection  = Database;
            cmd.CommandText = disableRollback;
            cmd.ExecuteNonQuery();

            //create tables
            new sqliteCommand(createTable + itemTableName + itemColumns, Database).ExecuteNonQuery();

            new sqliteCommand(createTable + playerTableName + playerColumns, Database).ExecuteNonQuery();
        }
コード例 #16
0
        public void Initialise(string connectionString)
        {
            m_connectionString = connectionString;

            m_log.Info("[ESTATE DB]: Sqlite - connecting: "+m_connectionString);

            m_connection = new SqliteConnection(m_connectionString);
            try
            {
                m_connection.Open();
            }
            catch (Exception ex)
            {
                throw new Exception("SQLite has errored out on opening the database. If you are on a 64 bit system, please run OpenSim.32BitLaunch.exe and try again. If this is not a 64 bit error :" + ex);
            }

            Assembly assem = GetType().Assembly;
            Migration m = new Migration(m_connection, assem, "EstateStore");
            m.Update();

            //m_connection.Close();
           // m_connection.Open();

            Type t = typeof(EstateSettings);
            m_Fields = t.GetFields(BindingFlags.NonPublic |
                                   BindingFlags.Instance |
                                   BindingFlags.DeclaredOnly);

            foreach (FieldInfo f in m_Fields)
                if (f.Name.Substring(0, 2) == "m_")
                    m_FieldMap[f.Name.Substring(2)] = f;
        }
コード例 #17
0
        /// <summary>
        /// Returns all categories.
        /// </summary>
        public IEnumerable<Category> GetAllCategories()
        {
            var categories = new List<Category>();

            using (var connection = new SqliteConnection("Data Source=" + dbPath))
            using (var query = new SqliteCommand("SELECT * FROM Categories", connection))
            {
                connection.Open();

                var reader = query.ExecuteReader(CommandBehavior.CloseConnection);

                while (reader.Read())
                {
                    var category = new Category();
                    category.Id = int.Parse(reader["id"].ToString());
                    category.Name = reader ["name"].ToString();

                    categories.Add(category);
                }

                reader.Close();
            }

            return categories;
        }
コード例 #18
0
        public SqliteVsMonoDSSpeedTests()
        {
            // create path and filename to the database file.
            var documents = Environment.GetFolderPath (
                Environment.SpecialFolder.Personal);
            _db = Path.Combine (documents, "mydb.db3");

            if (File.Exists (_db))
                File.Delete (_db);

            SqliteConnection.CreateFile (_db);
            var conn = new SqliteConnection("URI=" + _db);
            using (var c = conn.CreateCommand()) {
                c.CommandText = "CREATE TABLE DataIndex (SearchKey INTEGER NOT NULL,Name TEXT NOT NULL,Email Text NOT NULL)";
                conn.Open ();
                c.ExecuteNonQuery ();
                conn.Close();
            }
            conn.Dispose();

            // create path and filename to the database file.
            var documentsPath = Environment.GetFolderPath (Environment.SpecialFolder.MyDocuments);
            var libraryPath = Path.Combine (documentsPath, "..", "Library");
            _dataDirectory = Path.Combine (libraryPath, "MonoDS");
            _entity = "PersonEntity";
            _serializer = new Serializer();
        }
コード例 #19
0
ファイル: SqliteScreen.cs プロジェクト: dineshkummarc/Multi
 public static SqliteConnection GetConnection()
 {
     var documents = Environment.GetFolderPath (
         Environment.SpecialFolder.Personal);
     string db = Path.Combine (documents, "mydb.db3");
     bool exists = File.Exists (db);
     if (!exists)
         SqliteConnection.CreateFile (db);
     var conn = new SqliteConnection ("Data Source=" + db);
     if (!exists) {
         var commands = new[] {
             "CREATE TABLE People (Id INTEGER NOT NULL, FirstName ntext, LastName ntext, DateCreated datetime)",
             "INSERT INTO People (Id, FirstName, LastName, DateCreated) VALUES (1, 'Homer', 'Simpson', '2007-01-01 10:00:00')",
         };
         foreach (var cmd in commands){
             using (var c = conn.CreateCommand()) {
                 c.CommandText = cmd;
                 c.CommandType = CommandType.Text;
                 conn.Open ();
                 c.ExecuteNonQuery ();
                 conn.Close ();
             }
         }
     }
     return conn;
 }
コード例 #20
0
        /// <summary>
        /// Creates and opens a database.
        /// </summary>
        /// <param name="name">Database name.</param>
        /// <returns>Created database, or null if cannot be created.</returns>
        public override Database CreateDatabase(string name)
        {
            Database database = null;
            try
            {
                database = new Database(name, DEFAULT_DATABASE_OPTION_NEW, DEFAULT_DATABASE_OPTION_COMPRESS);
                string dbPath = Path.Combine(GetBasePath(), name);

                // Checks if a file already exists, if not creates the file.
                bool exists = File.Exists (dbPath);
                if (!exists)
                {
                    SqliteConnection.CreateFile (dbPath);
                }

                SqliteConnection connection = new SqliteConnection(
                    "Data Source=" + dbPath +
                    ",version=" + DEFAULT_DATABASE_VERSION);

                connection.Open();
                StoreConnection(name, connection);
                StoreDatabase(name, database);

            }
            catch (Exception e)
            {
                SystemLogger.Log(SystemLogger.Module.PLATFORM, "Exception creating database.", e);
                database = null;
            }

            return database;
        }
コード例 #21
0
 public SQLiteMonoTransformationProvider(Dialect dialect, string connectionString)
     : base(dialect, connectionString)
 {
     _connection = new SqliteConnection(_connectionString);
     _connection.ConnectionString = _connectionString;
     _connection.Open();
 }
コード例 #22
0
        public IDbConnection Get()
        {
            IDbConnection dbConnection = new SQL.SqliteConnection(connectionString);

            dbConnection.Open();
            return(dbConnection);
        }
コード例 #23
0
ファイル: CardsManager.cs プロジェクト: Tic-Tac-Toc/windbot
        public static void Init()
        {
            try
            {
                _cards = new Dictionary<int, CardData>();

                string currentPath = Assembly.GetExecutingAssembly().Location;
                currentPath = Path.GetDirectoryName(currentPath) ?? "";
                string absolutePath = Path.Combine(currentPath, "cards.cdb");

                if (!File.Exists(absolutePath))
                {
                    throw new Exception("Could not find the cards database.");
                }

                using (SqliteConnection connection = new SqliteConnection("Data Source=" + absolutePath))
                {
                    connection.Open();

                    const string select =
                        "SELECT datas.id, alias, type, level, race, attribute, atk, def, name, desc " +
                        "FROM datas INNER JOIN texts ON datas.id = texts.id";

                    using (SqliteCommand command = new SqliteCommand(select, connection))
                    using (SqliteDataReader reader = command.ExecuteReader())
                        InitCards(reader);
                }
            }
            catch (Exception ex)
            {
                throw new Exception("Could not initialize the cards database. Check the inner exception for more details.", ex);
            }
        }
コード例 #24
0
ファイル: DBManager.cs プロジェクト: rlaxodud214/Bow_Game
    internal static void DatabaseSQLAdd(string query) //삽입이라고 썼지만 삭제도 가능
    {
        IDbConnection dbConnection = new SqliteConnection(GetDBFilePath());

        dbConnection.Open();            // DB 열기
        dbCommand = dbConnection.CreateCommand();

        dbCommand.CommandText = query;  // 쿼리 입력
        try
        {
            dbCommand.ExecuteNonQuery();    // 쿼리 실행
        }

        catch (Exception e)
        {
            Debug.LogError(e);
            //test.text = e.ToString();
        }

        dbCommand.Dispose();
        dbCommand = null;
        dbConnection.Close();
        dbConnection = null;
        Debug.Log("데이터 삽입 완료");
        //test.text = "결과 데이터 삽입 완료";
    }
コード例 #25
0
ファイル: CardsManager.cs プロジェクト: duelqiuqiu/DevBot
        public static bool Init()
        {
            try
            {
                m_cards = new Dictionary <int, CardData>();

                string currentPath = System.Reflection.Assembly.GetExecutingAssembly().Location;
                currentPath = Path.GetDirectoryName(currentPath) ?? "";
                string absolutePath = Path.Combine(currentPath, "Content/cards.cdb");

                if (!File.Exists(absolutePath))
                {
                    return(false);
                }

                using (SQLiteConnection connection = new SQLiteConnection("Data Source=" + absolutePath))
                {
                    connection.Open();

                    const string select =
                        "SELECT datas.id, alias, type, level, race, attribute, atk, def, name, desc " +
                        "FROM datas INNER JOIN texts ON datas.id = texts.id";

                    SQLiteCommand command = new SQLiteCommand(select, connection);
                    using (SQLiteDataReader reader = command.ExecuteReader())
                        InitCards(reader);
                    command.Dispose();
                }
                return(true);
            }
            catch (Exception)
            {
                return(false);
            }
        }
コード例 #26
0
    public void ClickGameStart()
    {
        del_InsertNewUserInfo InsertInfo = () =>
        {
            string conn = "URI=file:" + Application.dataPath +
               "/StreamingAssets/GameUserDB/userDB.db";
            using (IDbConnection dbconn = new SqliteConnection(conn))
            {
                dbconn.Open(); //Open connection to the database.
                using (IDbCommand dbcmd = dbconn.CreateCommand())
                {
                    try
                    {
                        string sqlQuery =
                    "INSERT INTO USER_INFO(name, level, type) " +
                    "VALUES(" + "'" + chName.text + "'" + ", " +
                    "'" + chLevel.text + "'" + ", " +
                    "'" + chType.text + "'" + ")";

                        dbcmd.CommandText = sqlQuery;
                        dbcmd.ExecuteNonQuery();
                    }
                    catch(SqliteException e)
                    {
                        // 이미 등록된 캐릭터이다.
                        Debug.Log(e.Message);
                    }
                }
                dbconn.Close();
            }
        };
        InsertInfo();
        GameLoadingProcess();
    }
コード例 #27
0
ファイル: Repository.cs プロジェクト: alexsp17/SnookerByb
        private SqliteConnection openDbConnection()
        {
            var conn = new Mono.Data.Sqlite.SqliteConnection("Data Source=" + this.getDbFileName());

            conn.Open();
            return(conn);
        }
コード例 #28
0
ファイル: DrinksDatabaseADO.cs プロジェクト: Armoken/Learning
        public DrinkDatabase(string dbPath)
        {
            path = dbPath;
            // create the tables
            bool exists = File.Exists(dbPath);

            if (!exists)
            {
                connection = new SqliteConnection("Data Source=" + dbPath);

                connection.Open();
                var commands = new[] {
                    "CREATE TABLE [Items] (_id INTEGER PRIMARY KEY ASC, Name NTEXT, About NTEXT, Volume REAL, AlcoholByVolume REAL, IconNumber INTEGER);"
                };
                foreach (var command in commands)
                {
                    using (var c = connection.CreateCommand())
                    {
                        c.CommandText = command;
                        c.ExecuteNonQuery();
                    }
                }

                initializeValues();
            }
        }
コード例 #29
0
 public static List<DateTime> getHighScores()
 {
     List<DateTime> times = new List<DateTime>();
     string path = Application.persistentDataPath + "/Database.s3db"; //Path to database.
     if (File.Exists(path))
     {
         string sqlQuery;
         string conn = "URI=file:" + path;
         using (SqliteConnection dbconn = new SqliteConnection(conn))
         {
             dbconn.Open();
             sqlQuery = "CREATE TABLE IF NOT EXISTS HighScores(RunTime DATETIME)";
             using (IDbCommand cmd = (IDbCommand)new SqliteCommand(sqlQuery, dbconn))
             {
                 cmd.ExecuteNonQuery();
             }
             sqlQuery = "SELECT * " + "FROM HighScores";
             using (IDbCommand cmd = (IDbCommand)new SqliteCommand(sqlQuery, dbconn))
             {
                 using (IDataReader reader = cmd.ExecuteReader())
                 {
                     DateTime value;
                     while (reader.Read())
                     {
                         value = reader.GetDateTime(0); //passing 0 as we are reading from first column in 
                         times.Add(value);
                     }
                 }
             }
         }
         times.Sort();
     }
     return times;
 }
コード例 #30
0
        public override void OpenConnection()
        {
            ///<summary>
            /// uses already set connection string to re-open
            /// a closed connection
            /// </summary>
            /// <param>
            /// no public set params, uses _strConnection
            /// </param>


            #region OpenConnection_declarations
            #endregion

            #region OpenConnection_validaton
            #endregion

            #region OpenConnection_procedure
            // if connection not open then open
            if (_dbConn.State.ToString() != "Open")
            {
                _dbConn.ConnectionString = _strConnection;
                _dbConn.Open();
            }

            _strState = _dbConn.State.ToString();

            #endregion
        }
コード例 #31
0
        public List<Politician> LoadAllPoliticans()
        {
            var politicians = new List<Politician> ();

            using (var connection = new SqliteConnection (connectionString)) {
                using (var cmd = connection.CreateCommand ()) {
                    connection.Open ();
                    cmd.CommandText = String.Format ("SELECT bioguide_id, first_name, last_name,  govtrack_id, phone, party, state FROM Politician ORDER BY last_name");

                    using (var reader = cmd.ExecuteReader ()) {
                        while (reader.Read ()) {
                            politicians.Add (new Politician {
                                FirstName = reader ["first_name"].ToString (),
                                LastName = reader ["last_name"].ToString (),
                                BioGuideId = reader ["bioguide_id"].ToString (),
                                GovTrackId = reader ["govtrack_id"].ToString (),
                                Phone = reader ["phone"].ToString (),
                                State = reader ["state"].ToString (),
                                Party = reader ["party"].ToString ()
                            });
                        }
                    }
                }
            }
            return politicians;
        }
コード例 #32
0
        public void Initialise(string connectionString)
        {
            m_connectionString = connectionString;

            m_log.Info("[ESTATE DB]: Sqlite - connecting: "+m_connectionString);

            m_connection = new SqliteConnection(m_connectionString);
            m_connection.Open();

            Assembly assem = GetType().Assembly;
            Migration m = new Migration(m_connection, assem, "EstateStore");
            m.Update();

            //m_connection.Close();
           // m_connection.Open();

            Type t = typeof(EstateSettings);
            m_Fields = t.GetFields(BindingFlags.NonPublic |
                                   BindingFlags.Instance |
                                   BindingFlags.DeclaredOnly);

            foreach (FieldInfo f in m_Fields)
                if (f.Name.Substring(0, 2) == "m_")
                    m_FieldMap[f.Name.Substring(2)] = f;
        }
コード例 #33
0
        public Bill LoadFavoriteBill(int id)
        {
            Bill favBill;

            using (var connection = new SqliteConnection (connectionString)) {
                using (var cmd = connection.CreateCommand ()) {
                    connection.Open ();

                    cmd.CommandText = "SELECT * FROM FavoriteBills WHERE id = @id";
                    var idParam = new SqliteParameter ("@id", id);
                    cmd.Parameters.Add (idParam);

                    using (var reader = cmd.ExecuteReader ()) {
                        reader.Read ();
                        favBill = new Bill {
                            Id = Convert.ToInt32 (reader ["id"]),
                            Title = (string)reader ["title"],
                            ThomasLink = (string)reader ["thomas_link"],
                            Notes = reader["notes"] == DBNull.Value ? "" : (string)reader["notes"]
                        };
                    }
                }
            }

            return favBill;
        }
コード例 #34
0
        /// <summary>
        /// Returns all subscribed feeds.
        /// </summary>
        public IEnumerable<Feed> GetAllFeeds()
        {
            var feeds = new List<Feed>();

            using (var connection = new SqliteConnection("Data Source=" + dbPath))
            using (var query = new SqliteCommand("SELECT * FROM Feeds", connection))
            {
                connection.Open();

                var reader = query.ExecuteReader(CommandBehavior.CloseConnection);

                while (reader.Read())
                {
                    var feed = new Feed();
                    feed.Id = int.Parse(reader["id"].ToString());
                    feed.Name = reader ["name"].ToString();
                    feed.Url = reader ["url"].ToString();
                    feed.LastUpdated = DateTime.Parse (reader ["LastUpdated"].ToString ());
                    feed.CategoryId = int.Parse(reader["categoryId"].ToString());

                    feeds.Add(feed);
                }

                reader.Close();
            }

            return feeds;
        }
コード例 #35
0
ファイル: PreKeyring.cs プロジェクト: lixiaoyi1108/SecuruStik
        static PreKeyring()
        {
            try
            {
                log.Debug("Opening SQL connection...");
                PreKeyring.conn = new SqliteConnection();

                SqliteConnectionStringBuilder connStr = new SqliteConnectionStringBuilder();
                connStr.DataSource = Config.PrekeyringFile_Path;
                //connStr.Password = Config.PrekeyringFile_Password;
                PreKeyring.conn.ConnectionString = connStr.ToString();
                connectString = connStr.ToString();

                if ( Directory.Exists( Config.PrekeyringFile_Dir ) == false )
                    Directory.CreateDirectory( Config.PrekeyringFile_Dir );

                if ( File.Exists( Config.PrekeyringFile_Path ) == false )
                {
                    SqliteConnection.CreateFile( Config.PrekeyringFile_Path );
                    CreateTablesByStructures( PreKeyring.TableName );
                }
                conn.Open();
            }
            catch ( SqliteException ex )
            {
                SecuruStikException sex = new SecuruStikException( SecuruStikExceptionType.Init_Database,"SQLite - Create/Connect Failed." , ex );
                throw sex;
            }
            finally
            {
                PreKeyring.conn.Close();
            }
        }
コード例 #36
0
ファイル: SqliteDB.cs プロジェクト: pulb/basenji
        public static IDbConnection Open(string dbPath, bool create)
        {
            if (dbPath == null)
                throw new ArgumentNullException("dbPath");

            if (create) {
                if (File.Exists(dbPath))
                    File.Delete(dbPath);
            #if WIN32
                SQLiteConnection.CreateFile(dbPath);
            #else
                SqliteConnection.CreateFile(dbPath);
            #endif
            } else {
                if (!File.Exists(dbPath))
                    throw new FileNotFoundException(string.Format("Database '{0}' not found", dbPath));
            }

            IDbConnection conn;
            string connStr = string.Format("Data Source={0}", dbPath);
            #if WIN32
            conn = new SQLiteConnection(connStr);
            #else
            conn = new SqliteConnection(connStr);
            #endif
            conn.Open();
            return conn;
        }
コード例 #37
0
ファイル: SqliteTest.cs プロジェクト: jiwon8402/UnitySqlite
    // Use this for initialization
    void Start()
    {
        string conn = "URI=file:" + Application.dataPath + "/sqlite_userinfo";

        IDbConnection dbconn = new SqliteConnection(conn);
        dbconn.Open();
        IDbCommand dbcmd = dbconn.CreateCommand();

        string query = "SELECT idx, name, email FROM userinfo";
        dbcmd.CommandText = query;
        IDataReader reader = dbcmd.ExecuteReader();

        while(reader.Read())
        {
            int idx = reader.GetInt32(0);
            string name = reader.GetString(1);
            string email = reader.GetString(2);

            Debug.Log("idx : " + idx + ", name : " + name + ", email : " + email);
        }

        reader.Close();
        reader = null;
        dbcmd.Dispose();
        dbcmd = null;
        dbconn.Close();
        dbconn = null;
    }
コード例 #38
0
ファイル: folios.cs プロジェクト: BCMX/test
        //constructor
        static folios()
        {
            try {
                //conexion a DB
                var connection = new SqliteConnection(dbSource);
                connection.Open();

                //crear query
                var query = connection.CreateCommand();
                query.CommandText = "select consecutivo from folios where fecha='" + fecha + "'";

                //inicia en el folio de la DB
                generarConsecutivo=Convert.ToInt16(query.ExecuteScalar());

                //si el valor es 0, entonces creamos un nuevo renglon para ese dia
                //esto del 0 no necesariamente funciona en VistaDB
                if(generarConsecutivo.Equals(0))
                {
                    generarConsecutivo=1;
                    query = connection.CreateCommand();
                    query.CommandText = "insert into folios (fecha,consecutivo) values ('" + fecha + "'," + generarConsecutivo.ToString() + ")";
                    query.ExecuteNonQuery();
                }

                //cerrar conexion a DB
                connection.Close();

            } catch(Exception ex) {
                //en caso de error en la base de datos empezamos en 1
                generarConsecutivo=1;
            }
        }
コード例 #39
0
ファイル: PUBWap.cs プロジェクト: trloveu/che9app
 public string proDataExc(string[] strTT)
 {
     try
     {
         if (strTT.Length < 1) { return "No SQL"; }
         string DatabaseName = "PUB.db3";
         string documents = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);
         string db = System.IO.Path.Combine(documents, DatabaseName);
         var conn = new SqliteConnection("Data Source=" + db);
         var sqlitecmd = conn.CreateCommand();
         conn.Open();
         sqlitecmd.CommandType = CommandType.Text;
         for (int j = 0; j < strTT.Length; j++)
         {
             if (strTT[j] == "") { continue; }
             sqlitecmd.CommandText = strTT[j];
             sqlitecmd.ExecuteNonQuery();
         }
         conn.Close();
         conn.Dispose();
         return "";
     }
     catch (Exception Ex)
     {
         return Ex.ToString();
     }
 }
コード例 #40
0
        public bool ExcuteTransaction(string sql)
        {
            var cmds = sql.Split(';');
            using (SqliteConnection conn = new SqliteConnection(this.SqlConfig.ConnectionString))
            {
                conn.Open();
                SqliteCommand cmd = new SqliteCommand(conn);

                SqliteTransaction tran = conn.BeginTransaction();
                try
                {
                    foreach (var cmdSql in cmds)
                    {
                        cmd.CommandText = cmdSql;
                        cmd.ExecuteNonQuery();
                    }
                    tran.Commit();
                    conn.Close();
                    return true;
                }
                catch (Exception e)
                {
                    tran.Rollback();
                    conn.Close();
                    throw new Exception(e.Message + "  sql:" + sql);
                }
                finally
                {
                    conn.Close();
                }
            }
        }
コード例 #41
0
ファイル: SystemDB.cs プロジェクト: rockyx/DNT.Diag
    public void Open(string filePath)
    {
      if (_command != null)
        _command.Dispose();

      if (_conn != null)
        _conn.Close();

      try
      {
        ConnectionStringBuilder connstr = new ConnectionStringBuilder();
        _conn = new Connection();

        connstr.DataSource = (filePath.EndsWith("/") || filePath.EndsWith("\\")) ? filePath + "sys.db" : filePath + "/sys.db";
        _conn.ConnectionString = connstr.ToString();
        _conn.Open();

        _command = new Command(_conn);
        _command.CommandText = "SELECT Content FROM [Text] WHERE [Name]=:name AND [Language]=:language";
        _command.Parameters.Add(new Parameter(":name", DbType.Binary));
        _command.Parameters.Add(new Parameter(":language", DbType.Binary));
      }
      catch
      {
        if (_command != null)
          _command.Dispose();
        if (_conn != null)
          _conn.Dispose();

        _command = null;
        _conn = null;

        throw new DatabaseException("Cannot Open System Database");
      }
    }
コード例 #42
0
        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);

            DataTable dtArtists = new DataTable();

            #region fetch data for artists

            Mono.Data.Sqlite.SqliteConnection  cn      = new Mono.Data.Sqlite.SqliteConnection("library.sqlite");
            Mono.Data.Sqlite.SqliteCommand     comm    = new Mono.Data.Sqlite.SqliteCommand(cn);
            Mono.Data.Sqlite.SqliteDataAdapter adapter = new Mono.Data.Sqlite.SqliteDataAdapter(comm);
            comm.CommandText = @"
SELECT  name, id, fetched
FROM    artists
";
            adapter.Fill(dtArtists);

            #endregion

            if (dtArtists.Rows.Count == 0)
            {
                List <SubsonicItem> artists = Subsonic.GetIndexes();

                foreach (SubsonicItem artist in artists)
                {
                    DataRow dr = dtArtists.NewRow();
                    dr["name"]     = artist.name;
                    dr["id"]       = artist.id;
                    dr["feteched"] = DateTime.Now.ToString();
                    dtArtists.Rows.Add(dr);

                    comm             = new Mono.Data.Sqlite.SqliteCommand(cn);
                    comm.CommandText = @"
INSERT INTO artists (name, id, fetched)
VALUES(@name, @id, @fetched);
";
                    comm.Parameters.AddWithValue("@name", artist.name);
                    comm.Parameters.AddWithValue("@id", artist.id);
                    comm.Parameters.AddWithValue("@fetched", DateTime.Now.ToString());

                    if (cn.State != ConnectionState.Open)
                    {
                        cn.Open();
                    }
                    comm.ExecuteNonQuery();
                }

                if (cn.State != ConnectionState.Closed)
                {
                    cn.Close();
                }
            }

            rptArtists.DataSource = dtArtists;
            rptArtists.DataBind();
        }
コード例 #43
0
 public void Open()
 {
     try
     {
         m_Connection.Open();
     }
     catch (Exception ex)
     {
         Console.WriteLine("Open existing DB failed: " + ex);
     }
 }
コード例 #44
0
ファイル: CHighscoreDB.cs プロジェクト: venturion/Vocaluxe
        private bool _GetDataBaseSongInfos(int songID, out string artist, out string title, out int numPlayed, out DateTime dateAdded, string filePath)
        {
            artist    = String.Empty;
            title     = String.Empty;
            numPlayed = 0;
            dateAdded = DateTime.Today;

            using (var connection = new SQLiteConnection())
            {
                connection.ConnectionString = "Data Source=" + filePath;

                try
                {
                    connection.Open();
                }
                catch (Exception)
                {
                    return(false);
                }

                using (var command = new SQLiteCommand(connection))
                {
                    command.CommandText = "SELECT Artist, Title, NumPlayed, DateAdded FROM Songs WHERE [id] = @id";
                    command.Parameters.Add("@id", DbType.String, 0).Value = songID;

                    SQLiteDataReader reader;
                    try
                    {
                        reader = command.ExecuteReader();
                    }
                    catch (Exception)
                    {
                        return(false);
                    }

                    if (reader != null && reader.HasRows)
                    {
                        reader.Read();
                        artist    = reader.GetString(0);
                        title     = reader.GetString(1);
                        numPlayed = reader.GetInt32(2);
                        dateAdded = new DateTime(reader.GetInt64(3));
                        reader.Dispose();
                        return(true);
                    }
                    if (reader != null)
                    {
                        reader.Dispose();
                    }
                }
            }

            return(false);
        }
コード例 #45
0
        private string DBCreate()
        {
            //<summary><summary/>
            //<params><params/>
            //<output><output/>

            #region DBCreate_declarations
            string strPath   = Path.GetDirectoryName(Environment.GetCommandLineArgs()[0]);
            string strDBPath = strPath + "/" + _localDBName;
            var    testStr   = Path.GetPathRoot(strPath);
            #endregion

            #region DBCreate_validaton
            // Create the database if it doesn't already exist
            if (!File.Exists(strDBPath))
            {
                SqliteConnection.CreateFile(strDBPath);
            }
            else
            {
                return(strDBPath); //db exists so exit now and return default path
            }
            #endregion

            #region DBCreate_procedure
            // Create connection to the database
            var sqliteConn = new Mono.Data.Sqlite.SqliteConnection("Data Source=" + strDBPath);

            // Set the structure of the database
            if (File.Exists(strDBPath))
            {
                var sqliteCMD = new[] { "CREATE TABLE LocalSettings (Type TEXT, StringValue1 TEXT, StringValue2 TEXT, StringValue3 TEXT, StringValue4 TEXT, StringValue5 TEXT)" };

                sqliteConn.Open();
                foreach (var cmd in sqliteCMD)
                {
                    using (var c = sqliteConn.CreateCommand())
                    {
                        c.CommandText = cmd;
                        c.CommandType = System.Data.CommandType.Text;
                        c.ExecuteNonQuery();
                    }
                }
            }

            sqliteConn.Close();

            return(strDBPath);

            #endregion
        }
コード例 #46
0
 public bool InitConnection()
 {
     try
     {
         _SqlConnection.Open();
         _SqlCommand.Connection = _SqlConnection;
         return(true);
     }
     catch (Exception ex)
     {
         LogFault("Database connection failed.", ex, false);
         return(false);
     }
 }
コード例 #47
0
        public void CreateNew()
        {
            try
            {
                sqliteConnection.CreateFile(m_DataBaseName);

                m_Connection = new sqliteConnection("Data Source=" + m_DataBaseName + ";Version=3;FailIfMissing=True");
                m_Connection.Open();
            }
            catch (Exception ex)
            {
                Console.WriteLine("Create DB failed: " + ex);
            }
        }
コード例 #48
0
    public void MakeCvsThenSend()
    {
        /*Make CVS file*/
        //Filepath for the data.csv file
        string fileName = Application.persistentDataPath + "/" + "data.csv";

        //timestamp, page, date, feeling, urge, intensity, thoughts
        using (StreamWriter writer = new StreamWriter(fileName, false, Encoding.UTF8))
        {
            //Write the each columns title, for each field in pateint_info
            writer.Write("Timestamp | Page | Date | Feeling | Urge | Intensity | Thoughts");
            writer.Write(Environment.NewLine);

            //Write data from the the db
            conn = new sqliteConnection("URI=file:" + Application.persistentDataPath + "/" + dbName + ";Version=3;FailIfMissing=True;mode=cvs");
            conn.Open();
            var Sqlcommand = new sqliteCommand("select * from patient_info", conn);
            var reader     = Sqlcommand.ExecuteReader();
            while (reader.Read())
            {
                writer.Write(reader["timestamp"] + "|" + reader["page"] + "|" + reader["date"] + "|" + reader["feeling"] + "|" + reader["urge"] + "|" + reader["intensity"] + "|" + reader["thoughts"]);
                writer.Write(Environment.NewLine);
            }

            conn.Close();
        }


        /*SendMail*/
        MailMessage mail = new MailMessage();

        mail.From = new MailAddress("*****@*****.**");
        mail.To.Add(email.text);
        mail.Subject = "Patients Data from App";
        mail.Body    = "The File attached is the patients data (every entry is seperated by '|' when importing into excel or google sheets that custom seporator should be used) ";
        //Add the data.csv file to the email
        mail.Attachments.Add(new Attachment(fileName));

        SmtpClient smtpServer = new SmtpClient();

        smtpServer.Host           = "smtp.gmail.com";
        smtpServer.Port           = 587; //Has to be 587 so it works on Networks with port protections.
        smtpServer.DeliveryMethod = SmtpDeliveryMethod.Network;
        smtpServer.Credentials    = new System.Net.NetworkCredential("*****@*****.**", "HeartRateAppFxu2018") as ICredentialsByHost;
        smtpServer.EnableSsl      = true;
        ServicePointManager.ServerCertificateValidationCallback =
            delegate(object s, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
        { return(true); };
        smtpServer.Send(mail);
    }
コード例 #49
0
ファイル: CDatabaseBase.cs プロジェクト: da-ka/Vocaluxe
        public virtual bool Init()
        {
            lock (_Mutex)
            {
                if (_Connection != null)
                {
                    return(false);
                }
                _Connection = new SQLiteConnection("Data Source=" + _FilePath);
                try
                {
                    _Connection.Open();
                }
                catch (Exception)
                {
                    _Connection.Dispose();
                    _Connection = null;
                    return(false);
                }

                using (var command = new SQLiteCommand(_Connection))
                {
                    command.CommandText = "SELECT Value FROM Version";

                    SQLiteDataReader reader = null;

                    try
                    {
                        reader = command.ExecuteReader();
                    }
                    catch (Exception) {}

                    if (reader == null || !reader.Read() || reader.FieldCount == 0)
                    {
                        _Version = -1;
                    }
                    else
                    {
                        _Version = reader.GetInt32(0);
                    }

                    if (reader != null)
                    {
                        reader.Dispose();
                    }
                }
            }
            return(true);
        }
コード例 #50
0
ファイル: Program.cs プロジェクト: davidonete/Boom-Box
    public static void ModifyPlayerWinCount(uint ID, int value)
    {
        for (int i = 0; i < players.Count; i++)
        {
            if (players [i].ID == ID)
            {
                //Confirm log in credentials through database
                string   databasePath = "";
                Platform platform     = RunningPlatform();
                if (platform == Platform.Windows)
                {
                    databasePath = "Data Source=" + System.Environment.CurrentDirectory + "\\database.db; FailIfMissing=True";
                }
                else if (platform == Platform.Mac)
                {
                    databasePath = "Data Source=" + System.Environment.CurrentDirectory + "/data/database.db; FailIfMissing=True";
                }

                SQLiteConnection db_connection = new SQLiteConnection(databasePath);
                db_connection.Open();

                string        query   = "select * from Users where ID = @id";
                SQLiteCommand command = new SQLiteCommand(query, db_connection);
                command.Parameters.AddWithValue("@id", players[i].ID);

                SQLiteDataReader reader = command.ExecuteReader();

                if (reader.HasRows)
                {
                    while (reader.Read())
                    {
                        uint currentWinCount = Convert.ToUInt32(reader ["WINCOUNT"]);
                        players [i] = SetPlayerWinCount(players [i], currentWinCount + 1);

                        string sql = "update Users set WINCOUNT = @wincount where ID = @id";
                        command = new SQLiteCommand(sql, db_connection);
                        command.Parameters.AddWithValue("@wincount", currentWinCount + 1);
                        command.Parameters.AddWithValue("@id", players[i].ID);

                        command.ExecuteNonQuery();
                    }
                }

                db_connection.Close();
                break;
            }
        }
    }
コード例 #51
0
        public void IncreaseSongCounter(int dataBaseSongID)
        {
            using (var connection = new SQLiteConnection())
            {
                connection.ConnectionString = "Data Source=" + _FilePath;

                try
                {
                    connection.Open();
                }
                catch (Exception) {}

                using (var command = new SQLiteCommand(connection))
                    _IncreaseSongCounter(dataBaseSongID, command);
            }
        }
コード例 #52
0
    void Start() //When the Emergency Contacts Scene is opened Should display Contacts if they have been saved in the Database
    {
        conn = new sqliteConnection("URI=file:" + Application.persistentDataPath + "/" + dbName + ";Version=3;FailIfMissing=True");
        conn.Open();

        try
        {
            //Read from contact1 table and put that into text fields on the Emergency Contacts Screen
            var Sqlcommand = new sqliteCommand("select * from contact1", conn);
            var reader     = Sqlcommand.ExecuteReader();
            reader.Read();
            if (reader.HasRows == true)
            {
                name1.text         = reader["name"] as String;
                relationship1.text = reader["relationship"] as String;
                mobile1.text       = reader["mobile"] as String;
                home1.text         = reader["home"] as String;
            }
            else
            {
                Debug.Log("There are no rows in contact1");
            }

            //Read from contact2 table and put that into text fields on the Emergency Contacts Screen
            Sqlcommand = new sqliteCommand("select * from contact2", conn);
            reader     = Sqlcommand.ExecuteReader();
            reader.Read();
            if (reader.HasRows == true)
            {
                name2.text         = reader["name"] as String;
                relationship2.text = reader["relationship"] as String;
                mobile2.text       = reader["mobile"] as String;
                home2.text         = reader["home"] as String;
            }
            else
            {
                Debug.Log("There are no rows in contact2");
            }
        }
        catch (Exception ex)
        {
            Debug.Log("Failed to read from Database " + ex);
        }
        conn.Close();
    }
コード例 #53
0
        public static void Init()
        {
            connection = new SQLiteConnection();
            connection.ConnectionString = "Data Source=" + "logger.db";
            connection.Open();

            InitDefaultTables();

            NPCProto.sOnAttributeChanged   += _lcs_Attribute;
            NPCProto.sOnTalentValueChanged += _lcs_TalentValue;
            NPCProto.sOnTalentSkillChanged += _lcs_TalentSkill;
            NPCProto.sOnHitchancesChanged  += _lcs_Hitchances;

            //Events:
            Player.sOnPlayerSpawns      += _le_Spawn;
            Player.sOnPlayerDisconnects += _le_Disconnection;
            DamageScript.Damages        += _le_Damage;
        }
コード例 #54
0
 public static void Init(string absolutePath = "cards.cdb")
 {
     m_cards = new Dictionary <int, Card>();
     using (SQLiteConnection connection = new SQLiteConnection("Data Source=" + absolutePath)){
         connection.Open();
         using (SQLiteCommand command = new SQLiteCommand("SELECT datas.id, ot, alias, "
                                                          + "setcode, type, level, race, attribute, atk, def ,"
                                                          + " name , desc FROM datas,texts WHERE datas.id=texts.id",
                                                          connection)){
             using (SQLiteDataReader reader = command.ExecuteReader()){
                 while (reader.Read())
                 {
                     int           id        = reader.GetInt32(0);
                     int           ot        = reader.GetInt32(1);
                     int           levelinfo = reader.GetInt32(5);
                     int           level     = levelinfo & 0xff;
                     int           lscale    = (levelinfo >> 24) & 0xff;
                     int           rscale    = (levelinfo >> 16) & 0xff;
                     Card.CardData data      = new Card.CardData
                     {
                         Code      = id,
                         Alias     = reader.GetInt32(2),
                         Setcode   = reader.GetInt64(3),
                         Type      = reader.GetInt32(4),
                         Level     = level,
                         LScale    = lscale,
                         RScale    = rscale,
                         Race      = reader.GetInt32(6),
                         Attribute = reader.GetInt32(7),
                         Attack    = reader.GetInt32(8),
                         Defense   = reader.GetInt32(9)
                     };
                     string name = reader.GetString(10);
                     string desc = reader.GetString(11);
                     m_cards.Add(id, new Card(data, ot, name, desc));
                 }
                 reader.Close();
             }
         }
         connection.Close();
     }
 }
コード例 #55
0
ファイル: Database.cs プロジェクト: fatiangel/Xamarin
        //建立SQLite 資料庫
        void btnSQLite_TouchUpInside(object sender, EventArgs e)
        {
            var documents      = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
            var pathToDatabase = Path.Combine(documents, "normal.db");

            Mono.Data.Sqlite.SqliteConnection.CreateFile(pathToDatabase);

            var msg = "資料庫路徑為: " + pathToDatabase;

            //建立Table
            var connectionString = String.Format("Data Source={0};Version=3;", pathToDatabase);


            using (var conn = new Mono.Data.Sqlite.SqliteConnection(connectionString))
            {
                conn.Open();
                using (var cmd = conn.CreateCommand())
                {
                    cmd.CommandText = "CREATE TABLE People (PersonID INTEGER PRIMARY KEY AUTOINCREMENT , FirstName ntext, LastName ntext)";
                    cmd.CommandType = CommandType.Text;
                    cmd.ExecuteNonQuery();
                }
            }

            //新增資料
            using (var conn = new Mono.Data.Sqlite.SqliteConnection(connectionString))
            {
                conn.Open();
                using (var cmd = conn.CreateCommand())
                {
                    cmd.CommandText  = "Insert into People(FirstName,LastName) Values('Terry','Lin') ;";
                    cmd.CommandText += "Insert into People(FirstName,LastName) Values('Ben','Lu') ";
                    cmd.CommandType  = CommandType.Text;
                    cmd.ExecuteNonQuery();
                }
            }

            // 訊息輸出並停用Button
            lblmsg.Text            = msg;
            this.btnSQLite.Enabled = false;
        }
コード例 #56
0
        private string NewConnection(string strConnectionString)
        {
            //<summary><summary/>
            //<params><params/>
            //<output><output/>

            #region NewConnection_declarations
            string strDBPath = null;
            #endregion

            #region NewConnection_validaton
            if (string.IsNullOrWhiteSpace(strConnectionString))
            {
                strDBPath = _strConnection;
            }
            else
            {
                strDBPath = strConnectionString;
            }

            if (string.IsNullOrWhiteSpace(strDBPath))
            {
                throw new NullReferenceException(message: "Both strConnectionString and _strConnection are NULL.", innerException: new FileNotFoundException(message: "Default database doesn't exist.", fileName: Path.GetDirectoryName(Environment.GetCommandLineArgs()[0]) + _localDBName));
            }

            if (ConnectionState == "Open")
            {
                _dbConn.Close();
            }
            #endregion

            #region NewConnection_procedure
            // Create connection to the database
            _dbConn = new Mono.Data.Sqlite.SqliteConnection("Data Source=" + strDBPath);
            _dbConn.Open();
            _strState = _dbConn.State.ToString();

            return(strDBPath);

            #endregion
        }
コード例 #57
0
        public int AddScore(SPlayer player)
        {
            using (var connection = new SQLiteConnection())
            {
                connection.ConnectionString = "Data Source=" + _FilePath;

                try
                {
                    connection.Open();
                }
                catch (Exception)
                {
                    return(-1);
                }

                int medley    = 0;
                int duet      = 0;
                int shortSong = 0;
                switch (player.GameMode)
                {
                case EGameMode.TR_GAMEMODE_MEDLEY:
                    medley = 1;
                    break;

                case EGameMode.TR_GAMEMODE_DUET:
                    duet = 1;
                    break;

                case EGameMode.TR_GAMEMODE_SHORTSONG:
                    shortSong = 1;
                    break;
                }

                using (var command = new SQLiteCommand(connection))
                {
                    int dataBaseSongID = CSongs.GetSong(player.SongID).DataBaseSongID;
                    return(_AddScore(CProfiles.GetPlayerName(player.ProfileID), (int)Math.Round(player.Points), player.VoiceNr, player.DateTicks, medley,
                                     duet, shortSong, (int)CProfiles.GetDifficulty(player.ProfileID), dataBaseSongID, command));
                }
            }
        }
コード例 #58
0
ファイル: DBManager.cs プロジェクト: rlaxodud214/Bow_Game
    internal static void DbConnectionCHek()
    {
        try
        {
            IDbConnection dbConnection = new SqliteConnection(GetDBFilePath());
            dbConnection.Open();                            // DB열기

            if (dbConnection.State == ConnectionState.Open) // DB상태가 잘 열렸다면
            {
                Debug.Log("DB 연결 성공");
            }
            else
            {
                Debug.Log("DB 연결 실패");
            }
        }
        catch (Exception e)
        {
            Debug.Log(e);
        }
    }
コード例 #59
0
        /// <summary>
        /// Executing SQL statements
        /// </summary>
        /// <param name="DB">Database</param>
        /// <param name="SQLs">SQL statement</param>
        /// <returns>Returns the number of rows affected</returns>
        public static int Command(string DB, params string[] SQLs)
        {
            int result = 0;

            if (File.Exists(DB) && SQLs != null)
            {
                using (SQLiteConnection con = new SQLiteConnection(@"Data Source=" + DB))
                {
                    con.Open();
                    using (SQLiteTransaction trans = con.BeginTransaction())
                    {
                        try
                        {
                            using (SQLiteCommand cmd = new SQLiteCommand(con))
                            {
                                foreach (string SQLstr in SQLs)
                                {
                                    cmd.CommandText = SQLstr;
                                    result         += cmd.ExecuteNonQuery();
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            Console.WriteLine(ex.ToString());
                            trans.Rollback();                            //There was an error, roll back
                            result = -1;
                        }
                        finally
                        {
                            try{
                                trans.Commit();
                            }catch { }
                        }
                    }
                    con.Close();
                }
            }
            return(result);
        }
コード例 #60
0
        public SQLDatabase(String dataBaseName, bool exists)
        {
            m_DataBaseName = dataBaseName;

            if (exists)
            {
                try
                {
                    m_Connection = new sqliteConnection("Data Source=" + m_DataBaseName + ";Version=3;FailIfMissing=True");
                    m_Connection.Open();
                }
                catch (Exception ex)
                {
                    Console.WriteLine("Open DB failed: " + ex);
                }
            }
            else
            {
                m_TableList = new List <SQLTable>();
                CreateNew();
            }
        }