public static async Task ModifyWebShellAsync(CWebShellInfo info) { SqliteConnection sqliteConnection = null; SqliteCommand sqliteCommand = null; string strDatabasePath = ApplicationData.Current.LocalFolder.Path + "\\" + m_DatabasePath + "\\" + m_DatabaseFile; try { sqliteConnection = new SqliteConnection(string.Format("Filename={0}", strDatabasePath)); await sqliteConnection.OpenAsync(); //插入数据 string strInsert = string.Format("update WebShell set URL=\'{0}\',PASSWORD=\'{1}\',TYPE=\'{2}\',REMARK=\'{3}\',ENCODING=\'{4}\' where GUID=\'{5}\'", info.Url, info.Password, info.Type.ToString(), info.Remark, info.Encoding, info.Guid.ToString()); sqliteCommand = new SqliteCommand(strInsert, sqliteConnection); sqliteCommand.ExecuteReader(); } catch (Exception e) { throw; } finally { sqliteConnection?.Dispose(); sqliteCommand?.Dispose(); } }
public static async Task DeleteWebShellAsync(Guid guid) { SqliteConnection sqliteConnection = null; SqliteCommand sqliteCommand = null; string strDatabasePath = ApplicationData.Current.LocalFolder.Path + "\\" + m_DatabasePath + "\\" + m_DatabaseFile; try { sqliteConnection = new SqliteConnection(string.Format("Filename={0}", strDatabasePath)); await sqliteConnection.OpenAsync(); //删除数据 string strDelete = string.Format("delete from WebShell where GUID=\'{0}\'", guid.ToString()); sqliteCommand = new SqliteCommand(strDelete, sqliteConnection); sqliteCommand.ExecuteReader(); } catch (Exception e) { throw; } finally { sqliteConnection?.Dispose(); sqliteCommand?.Dispose(); } }
public void Dispose() { reader?.Close(); reader?.Dispose(); command?.Dispose(); connection.Close(); connection.Dispose(); connection = null; }
public static async Task AddWebShellAsync(CWebShellInfo info) { try { //判断文件夹在不在 var items = await ApplicationData.Current.LocalFolder.GetFolderAsync("Database"); } catch (Exception e) { if ((uint)e.HResult == 0x80070002) { await ApplicationData.Current.LocalFolder.CreateFolderAsync("Database"); } else { throw; } } SqliteConnection sqliteConnection = null; SqliteCommand sqliteCommand = null; string strDatabasePath = ApplicationData.Current.LocalFolder.Path + "\\" + m_DatabasePath + "\\" + m_DatabaseFile; try { sqliteConnection = new SqliteConnection(string.Format("Filename={0}", strDatabasePath)); sqliteConnection.Open(); //表初始化 string strWebShellDataInit = "create table if not exists WebShell(GUID CHAR(38) PRIMARY KEY, URL VARCHAR(2048), PASSWORD VARCHAR(2048), TYPE VARCHAR(32), REMARK VARCHAR(4096),ENCODING VARCHAR(32),CREATETIME INTEGER)"; sqliteCommand = new SqliteCommand(strWebShellDataInit, sqliteConnection); sqliteCommand.ExecuteReader(); sqliteCommand.Dispose(); //插入数据 string strInsert = string.Format("insert into WebShell(GUID,URL,PASSWORD,TYPE,REMARK,ENCODING,CREATETIME) VALUES (\'{0}\',\'{1}\',\'{2}\',\'{3}\',\'{4}\',\'{5}\',{6})", info.Guid.ToString(), info.Url, info.Password, info.Type.ToString(), info.Remark, info.Encoding, info.CreateTime); sqliteCommand = new SqliteCommand(strInsert, sqliteConnection); sqliteCommand.ExecuteReader(); } catch (Exception e) { throw; } finally { sqliteConnection?.Dispose(); sqliteCommand?.Dispose(); } }
/* * 获取所有Webshell信息 * 如果没有对应的表,会创建一个 * Webshell基本信息: * GUID:每个webshell拥有一个,不重复 * URL:地址 * Password:密码 * Type:指定是什么类型:php5,php7,aspx等 * Encoding:内容的编码,UTF8 UTF16 GBK等 * Remark:用户写的备注 */ public static async Task <List <CWebShellInfo> > QueryAllWebShell() { List <CWebShellInfo> infoList = new List <CWebShellInfo>(); string str = ApplicationData.Current.LocalFolder.Path + "\\" + m_DatabasePath + "\\" + m_DatabaseFile; SqliteConnection sqliteConnection = null; SqliteCommand commandQueryAllWebShell = null; SqliteDataReader reader = null; try { sqliteConnection = new SqliteConnection(string.Format("Filename={0}", str)); await sqliteConnection.OpenAsync(); string strQueryAllWebShellData = "select * from WebShell"; commandQueryAllWebShell = new SqliteCommand(strQueryAllWebShellData, sqliteConnection); reader = commandQueryAllWebShell.ExecuteReader(); while (reader.Read()) { string strUrl = reader["URL"].ToString(); string strPassword = reader["PASSWORD"].ToString(); string strType = reader["TYPE"].ToString(); string strRemark = reader["REMARK"].ToString(); string strEncoding = reader["ENCODING"].ToString(); string strGuid = reader["GUID"].ToString(); Int64 i64CreateTime = Convert.ToInt64(reader["CREATETIME"]); infoList.Add(new CWebShellInfo(strUrl, strPassword, strRemark, new Guid(strGuid), (WebShellType)Enum.Parse(typeof(WebShellType), strType, true), strEncoding, i64CreateTime)); } } catch (Exception e) { if ((uint)e.HResult != 0x80004005) { throw; } } finally { sqliteConnection?.Dispose(); commandQueryAllWebShell?.Dispose(); } return(infoList); }
public static void TestPatientLabelPointsDrop() { using (var conn = new SqliteConnection(GlobalController.path)) { conn.Open(); PontosRotuloPaciente.Drop(); var check = "SELECT count(*) FROM sqlite_master WHERE type='table' AND name='PONTOSROTULOPACIENTE';"; var result = 0; using (var cmd = new SqliteCommand(check, conn)) { using (IDataReader reader = cmd.ExecuteReader()) { try { while (reader.Read()) { if (!reader.IsDBNull(0)) { result = reader.GetInt32(0); } } } finally { reader.Dispose(); reader.Close(); } } cmd.Dispose(); } Assert.AreEqual(result, 0); conn.Dispose(); conn.Close(); } return; }
public string GetSMSTextBodyTemplateByCategoryID(int CategoryID) { string sql = @"SELECT c.TxtBodyTemplate FROM TbL_Categories as c where c.id = " + CategoryID + ";"; using (SqliteCommand command = new SqliteCommand(sql, m_dbConnection)) { SqliteDataReader dr = command.ExecuteReader(); if (dr.HasRows) { while (dr.Read()) { return(dr.GetString(0)); } } command.Dispose(); } return(null); }
static public void CloseDB() { if (dbCommand != null) { dbCommand.Dispose(); } dbCommand = null; if (reader != null) { reader.Dispose(); } reader = null; if (dbConnection != null) { dbConnection.Close(); } dbConnection = null; Debug.Log("Disconnected from db."); Log.WriteLog("Disconnected from db."); }
public IEnumerable <Slot> GetSlots() { using (SqliteCommand cmd = conn.CreateCommand()) { cmd.CommandText = selectAllCommand; using (SqliteDataReader rdr = cmd.ExecuteReader()) { while (rdr.Read()) { // Was unable to identify a way to automate the DAO mapping with Mono.Data.Sqlite yield return(new Slot(rdr.GetInt64(rdr.GetOrdinal("id")), rdr.GetDateTime(rdr.GetOrdinal("start")), rdr.GetDateTime(rdr.GetOrdinal("end")), rdr.GetString(rdr.GetOrdinal("description")), rdr.GetString(rdr.GetOrdinal("project")))); } } cmd.Dispose(); } }
public static void Create(string query) { using (var conn = new SqliteConnection(GlobalController.path)) { conn.Open(); var sqlQuery = query; using (var cmd = new SqliteCommand(sqlQuery, conn)) { cmd.ExecuteNonQuery(); cmd.Dispose(); } conn.Dispose(); conn.Close(); SqliteConnection.ClearAllPools(); GC.Collect(); GC.WaitForPendingFinalizers(); } }
// =================================================================================== /// <summary>Executes the non query SQL.</summary> /// <param name="sqlString">SQL string.</param> private void ExecuteNonQuerySql(string sqlString) { SqliteCommand Cmd = null; try { Cmd = Connection.CreateCommand(); Cmd.CommandText = sqlString; Cmd.CommandType = System.Data.CommandType.Text; Cmd.ExecuteNonQuery(); } catch (SqliteException ex) { Console.WriteLine("Error: {0}", ex.ToString()); } finally { Cmd.Dispose(); } }
public void CloseSqlConnection() { if (_dbCommand != null) { _dbCommand.Dispose(); } _dbCommand = null; if (_reader != null) { _reader.Dispose(); } _reader = null; if (_dbConnection != null) { _dbConnection.Close(); } _dbConnection = null; Log.UILog("Disconnected from db " + _name); }
public static int ExecuteNonQuery(SqliteCommand cmd) { if (cmd == null || cmd.Connection == null) { throw new NullReferenceException("command or Connection"); } if (cmd.Connection.State == ConnectionState.Closed) { cmd.Connection.Open(); } if (cmd.Connection.State == ConnectionState.Closed) { cmd.Connection.Open(); } int result = cmd.ExecuteNonQuery(); cmd.Connection.Close(); cmd.Dispose(); return(result); }
public void CloseSqlConnection() { if (dbCommand != null) { dbCommand.Dispose(); } dbCommand = null; if (reader != null) { reader.Dispose(); } reader = null; if (dbConnection != null) { dbConnection.Close(); } dbConnection = null; }
/** * Função que deleta dados cadastrados anteriormente na relação de pessoas. */ public static void DeleteValue(int tableId, int id) { using (var conn = new SqliteConnection(GlobalController.path)) { conn.Open(); var sqlQuery = string.Format("delete from \"{0}\" WHERE \"{1}\" = \"{2}\"", TablesManager.Tables[tableId].tableName, TablesManager.Tables[tableId].colName[0], id); using (var cmd = new SqliteCommand(sqlQuery, conn)) { cmd.ExecuteNonQuery(); cmd.Dispose(); } conn.Dispose(); conn.Close(); SqliteConnection.ClearAllPools(); GC.Collect(); GC.WaitForPendingFinalizers(); } }
public static void AddData(Database Data_in) { using (SqliteConnection db = new SqliteConnection("Filename=faToken.db")) { db.Open(); SqliteCommand insertCommand = new SqliteCommand(); insertCommand.Connection = db; // Use parameterized query to prevent SQL injection attacks insertCommand.CommandText = "INSERT INTO MyTable VALUES (NULL, @Token,@Folder);"; insertCommand.Parameters.AddWithValue("@Token", Data_in.Token); insertCommand.Parameters.AddWithValue("@Folder", Data_in.Folder); insertCommand.ExecuteReader(); insertCommand.Dispose(); db.Close(); db.Dispose(); } }
static public void CloseDB() { if (dbCommand != null) { dbCommand.Dispose(); } dbCommand = null; if (reader != null) { reader.Dispose(); } reader = null; if (dbConnection != null) { dbConnection.Close(); } dbConnection = null; Log.WriteLog("Disconnected from db."); //MonoBehaviour.print("Disconnected from db."); }
/// <summary> /// 关闭数据库连接 /// </summary> public void CloseSqlConnection() { if (Command != null) { Command.Dispose(); } Command = null; if (Reader != null) { Reader.Dispose(); } Reader = null; if (Connection != null) { Connection.Close(); } Connection = null; Debug.Log("close from db."); }
// ================================= OTHER ======================================= // ------------------------------------------------------------------------------- // CloseDatabase // ------------------------------------------------------------------------------- protected void CloseDatabase() { if (_reader != null && !_reader.IsClosed) { _reader.Close(); } _reader = null; if (_command != null) { _command.Dispose(); } _command = null; if (_connection != null && _connection.State != ConnectionState.Closed) { _connection.Close(); } _connection = null; }
public void CheckPaymentTypeTable() { using (_connection) { _connection.Open(); SqliteCommand dbcmd = _connection.CreateCommand(); dbcmd.CommandText = @"CREATE TABLE IF NOT EXISTS `PaymentType` ( `Id` INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, `CustomerId` TEXT NOT NULL, `AccountNumber` TEXT NOT NULL, `Name` TEXT NOT NULL )"; dbcmd.ExecuteNonQuery(); dbcmd.Dispose(); _connection.Close(); } }
public void Close() { if (m_SqlCommand != null) { m_SqlCommand.Dispose(); m_SqlCommand = null; } if (m_SqlDataReader != null) { m_SqlDataReader.Dispose(); m_SqlDataReader = null; } if (m_SqlConnection != null) { m_SqlConnection.Close(); m_SqlConnection = null; } }
public void CloseSqlConnection() { if (dbCommand != null) { dbCommand.Dispose(); } dbCommand = null; if (reader != null) { reader.Dispose(); } reader = null; if (dbConnection != null) { dbConnection.Close(); } dbConnection = null; Debug.WriteLine("Disconnected from db."); }
public static void TestPacienteCreate() { using (var conn = new SqliteConnection(GlobalController.path)) { conn.Open(); // tabela sendo criada no SetUp, no "Initialize" da GlobalController var check = "SELECT count(*) FROM sqlite_master WHERE type='table' AND name='PACIENTE';"; var result = 0; using (var cmd = new SqliteCommand(check, conn)) { using (IDataReader reader = cmd.ExecuteReader()) { try { while (reader.Read()) { if (!reader.IsDBNull(0)) { result = reader.GetInt32(0); } } } finally { reader.Dispose(); reader.Close(); } } cmd.Dispose(); } Assert.AreEqual(result, 1); conn.Dispose(); conn.Close(); } }
/// <summary> /// 执行指定的 SQL 命令,并返回受影响的记录数。 /// </summary> /// <param name="Command">要执行的命令。</param> /// <returns></returns> public override int ExecuteNoneQuery(CommandBuilder Command) { ClearError(); SqliteCommand DbCommand = new SqliteCommand(); try { DbCommand.Connection = (SqliteConnection)Connect(); DbCommand.CommandText = Command.Parsing(parserAdapter); foreach (object p in Command.CommandParameters) { DbCommand.Parameters.Add((SqliteParameter)p); } DbCommand.CommandType = Command.CommandType; int result = DbCommand.ExecuteNonQuery(); if (result > 0) { QueryLastIdentity(DbCommand); } return(result <= 0 ? 1 : result); } catch (Exception Ex) { _Error = new DbError(Ex.Message, DbCommand.CommandText, ConnectionString); return(-1); } finally { if (ConnectionPoolAvailable) { ConnectionPool.ReleaseConnection(DbCommand.Connection); } else { DbCommand.Connection.Close(); DbCommand.Connection.Dispose(); } DbCommand.Parameters.Clear(); DbCommand.Dispose(); } }
/// <summary> /// Opens and executes operations on the database. /// </summary> /// <param name="limit">Limit of last records from the database.</param> /// <returns>Status of the operation.</returns> public List <BrHistory> GetHistoryFromDatabase(long limit) { var bhHistory = new BrHistory(); List <BrHistory> bHistories = new List <BrHistory>(); try { StringBuilder SQLqueryStandard = new StringBuilder("SELECT urls.url,urls.title, (visits.visit_time / 1000000 + (strftime('%s', '1601-01-01'))), visits.visit_duration FROM visits INNER JOIN urls ON visits.url=urls.id WHERE visits.visit_time order by visits.id desc limit $;"); SQLqueryStandard.Replace("$", limit.ToString()); if (GetDataBase()) { var sqliteConnection = new SqliteConnection("Data Source=" + Environment.GetFolderPath(Environment.SpecialFolder .LocalApplicationData) + @"\SP\" + _accountProfile.GetName() + @"\History_COPY.db"); sqliteConnection.Open(); var dbCommand = new SqliteCommand(SQLqueryStandard.ToString(), sqliteConnection); SqliteDataReader dataReader = dbCommand.ExecuteReader(); while (dataReader.Read()) { bHistories.Add(new BrHistory(dataReader.GetString(0), dataReader.GetString(1), dataReader.GetInt64(2), dataReader.GetInt64(3))); } sqliteConnection.Close(); sqliteConnection.Dispose(); dbCommand.Dispose(); return(bHistories); } return(null); } catch (Exception f) { Debug.WriteLine(f); throw; } finally { RemoveCopy(); } }
public static void TestSessionDrop() { using (var conn = new SqliteConnection(GlobalController.path)) { conn.Open(); Sessao.Drop(); var check = "SELECT count(*) FROM sqlite_master WHERE type='table' AND name='SESSAO';"; var result = 0; using (var cmd = new SqliteCommand(check, conn)) { using (IDataReader reader = cmd.ExecuteReader()) { try { while (reader.Read()) { if (!reader.IsDBNull(0)) { result = reader.GetInt32(0); } } } finally { reader.Dispose(); reader.Close(); } } cmd.Dispose(); } Assert.AreEqual(result, 0); conn.Dispose(); conn.Close(); } }
/// <summary> /// Command which edits an existing publication record via Record ID /// </summary> /// <param name="publication"></param> public void EditPublication(Publication publication) { using (SqliteConnection conn = new SqliteConnection(DBConnection.GetConnectionString())) { using (SqliteCommand comm = new SqliteCommand(EditPublicationCommandText(), conn)) { comm.Parameters.AddWithValue("@PublicationId", publication.ID); comm.Parameters.AddWithValue("@Title", publication.Title); comm.Parameters.AddWithValue("@Group", publication.Group); comm.Parameters.AddWithValue("@Location", publication.Location); comm.Parameters.AddWithValue("@Summary", publication.Summary); comm.Parameters.AddWithValue("@Date", publication.Date); if (publication.RangeUsed) { comm.Parameters.AddWithValue("@RangeDate", publication.EndOfRange); } else { comm.Parameters.AddWithValue("@RangeDate", publication.Date); } comm.Parameters.AddWithValue("@RangeUsed", publication.RangeUsed); comm.Connection.Open(); try { comm.Transaction = comm.Connection.BeginTransaction(); comm.ExecuteNonQuery(); comm.Transaction.Commit(); } catch (Exception) { throw; } finally { comm.Connection.Close(); comm.Connection.Dispose(); comm.Dispose(); } } } }
/// <summary> /// Returns a full collection of all publications stored in the database /// </summary> /// <returns></returns> public ObservableCollection <Publication> GetCollectionOfPublications() { using (SqliteConnection conn = new SqliteConnection(DBConnection.GetConnectionString())) { using (SqliteCommand comm = new SqliteCommand(GetCollectionOfPublicationsCommandText(), conn)) { ObservableCollection <Publication> returnList = new ObservableCollection <Publication>(); comm.Connection.Open(); SqliteDataReader reader = comm.ExecuteReader(); try { while (reader.Read()) { Publication retrievedPublication = new Publication() { ID = reader.GetSafeInt("PublicationId"), Group = reader.GetSafeString("ItemGroup"), Title = reader.GetSafeString("Title"), Location = reader.GetSafeString("Location"), Summary = reader.GetSafeString("Summary"), Date = reader.GetSafeDateTime("Date"), EndOfRange = reader.GetSafeDateTime("RangeDate"), RangeUsed = reader.GetSafeBool("RangeUsed") }; returnList.Add(retrievedPublication); } return(returnList); } catch (Exception) { throw; } finally { comm.Connection.Close(); comm.Connection.Dispose(); comm.Dispose(); } } } }
public void CheckAccountTable() { using (_connection) { _connection.Open(); SqliteCommand dbcmd = _connection.CreateCommand(); // Query the account table to see if table is created dbcmd.CommandText = $"SELECT `Id` FROM `Account`"; try { // Try to run the query. If it throws an exception, create the table using (SqliteDataReader reader = dbcmd.ExecuteReader()) { } dbcmd.Dispose(); } catch (Microsoft.Data.Sqlite.SqliteException ex) { Console.WriteLine(ex.Message); if (ex.Message.Contains("no such table")) { dbcmd.CommandText = $@"CREATE TABLE `Account` ( `Id` INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, `Customer` TEXT NOT NULL, `Balance` REAL NOT NULL DEFAULT 0 )"; try { dbcmd.ExecuteNonQuery(); } catch (Microsoft.Data.Sqlite.SqliteException crex) { Console.WriteLine(crex); Console.WriteLine("Table already exists. Ignoring"); } } } _connection.Close(); } }
static DBUcionica() { // Instanciranje SQL komande SqliteCommand com = DB.con.CreateCommand(); // DROP TABLE IF EXISTS Ucionica; com.CommandText = @" CREATE TABLE IF NOT EXISTS Ucionica( ID integer primary key autoincrement, naziv nvarchar(32), kapacitet nvarchar(32), komentar nvarchar(32), polje_IDpredavaca nvarchar(200), CONSTRAINT NAZIV_unique UNIQUE(naziv))" ; // izvršavanje SQL naredbe koja ne vraća rezultate (nije upit) com.ExecuteNonQuery(); // otpuštanje resursa com.Dispose(); }
protected void CloseCommand(SqliteCommand cmd) { cmd.Connection.Close(); cmd.Connection.Dispose(); cmd.Dispose(); }
public bool SetToken(UUID principalID, string token, int lifetime) { if (System.Environment.TickCount - m_LastExpire > 30000) DoExpire(); SqliteCommand cmd = new SqliteCommand("insert into tokens (UUID, token, validity) values ('" + principalID.ToString() + "', '" + token + "', datetime('now', 'localtime', '+" + lifetime.ToString() + " minutes'))"); if (ExecuteNonQuery(cmd, m_Connection) > 0) { cmd.Dispose(); return true; } cmd.Dispose(); return false; }
public bool CheckToken(UUID principalID, string token, int lifetime) { if (System.Environment.TickCount - m_LastExpire > 30000) DoExpire(); SqliteCommand cmd = new SqliteCommand("update tokens set validity = datetime('now', 'localtime', '+" + lifetime.ToString() + " minutes') where UUID = '" + principalID.ToString() + "' and token = '" + token + "' and validity > datetime('now', 'localtime')"); if (ExecuteNonQuery(cmd, m_Connection) > 0) { cmd.Dispose(); return true; } cmd.Dispose(); return false; }
private void DoExpire() { SqliteCommand cmd = new SqliteCommand("delete from tokens where validity < datetime('now', 'localtime')"); ExecuteNonQuery(cmd, m_Connection); cmd.Dispose(); m_LastExpire = System.Environment.TickCount; }
public override long InsertWithOnConflict (String table, String nullColumnHack, ContentValues initialValues, ConflictResolutionStrategy conflictResolutionStrategy) { if (!String.IsNullOrWhiteSpace(nullColumnHack)) { var e = new InvalidOperationException("{0} does not support the 'nullColumnHack'.".Fmt(Tag)); Log.E(Tag, "Unsupported use of nullColumnHack", e); throw e; } var command = GetInsertCommand(table, initialValues, conflictResolutionStrategy); var lastInsertedId = -1L; try { command.ExecuteNonQuery(); // Get the new row's id. // TODO.ZJG: This query should ultimately be replaced with a call to sqlite3_last_insert_rowid. var lastInsertedIndexCommand = new SqliteCommand("select last_insert_rowid()", Connection, currentTransaction); lastInsertedId = (Int64)lastInsertedIndexCommand.ExecuteScalar(); lastInsertedIndexCommand.Dispose(); if (lastInsertedId == -1L) { Log.E(Tag, "Error inserting " + initialValues + " using " + command.CommandText); } else { Log.V(Tag, "Inserting row " + lastInsertedId + " from " + initialValues + " using " + command.CommandText); } } catch (Exception ex) { Log.E(Tag, "Error inserting into table " + table, ex); } finally { command.Dispose(); } return lastInsertedId; }