public void DataCount(string table_name,out int count) { count=0; DbCommand = DbConnection.CreateCommand(); DbCommand.CommandText = "SELECT COUNT(*) FROM " + table_name; count = System.Convert.ToInt32(DbCommand.ExecuteScalar()); }
public bool register(String name, String password) { if (existsName(name)) { return(false); } //Setting default parameter! Can be overwritten by other modules, after registration! player.setSpawnInfos(@"NEWWORLD\NEWWORLD.ZEN", null, null); player.HPMax = 10; player.HP = 10; using (SQLiteCommand command = new SQLiteCommand(Sqlite.getSqlite().connection)) { command.CommandText = "INSERT INTO `account` ("; command.CommandText += " `id`, `name`, `password`, `posx`, `posy`, `posz`, `world`)"; command.CommandText += "VALUES( NULL, @name, @password, @posx, @posy, @posz, @world)"; command.Parameters.AddWithValue("@name", name); command.Parameters.AddWithValue("@password", password); command.Parameters.AddWithValue("@posx", 0); command.Parameters.AddWithValue("@posy", 0); command.Parameters.AddWithValue("@posz", 0); command.Parameters.AddWithValue("@world", player.Map); command.ExecuteNonQuery(); command.CommandText = @"select last_insert_rowid()"; accountID = (long)command.ExecuteScalar(); } state = State.LoggedIn; return(true); }
public bool ExecuteScalar(ref object pQueryResult, bool bKillConnectionOnError = false) { if (_SqlConnection.State != System.Data.ConnectionState.Open || _SqlCommand.Connection == null) { throw new Exception("Connection not initialised"); } try { pQueryResult = _SqlCommand.ExecuteScalar(); return(true); } catch (Exception ex) { pQueryResult = null; LogFault(String.Format("Query execution failed {0}.", _SqlCommand.CommandText), ex, true); if (bKillConnectionOnError) { Dispose(); } return(false); } }
/// <summary> /// Allows the programmer to retrieve single items from the DB. /// </summary> /// <param name="sql">The query to run.</param> /// <returns>A string.</returns> public string ExecuteScalar(string sql) { SqliteConnection cnn = new SqliteConnection(dbConnection); cnn.Open(); SqliteCommand cmd = new SqliteCommand(cnn) { CommandText = sql }; object value = cmd.ExecuteScalar(); if (value != null) return value.ToString(); else return ""; }
public static int ExecuteIntCommand(SqliteCommand command) { try { return Convert.ToInt32(command.ExecuteScalar()); } catch (Exception ex) { MessageBox.Show(ex.Message); return -1; } }
//判断表是否存在 public bool IsTableExist(string table_name) { if (table_name == null) { return false; } DbCommand = DbConnection.CreateCommand(); DbCommand.CommandText = "SELECT COUNT(*) FROM sqlite_master WHERE TYPE='table' AND NAME='"+ table_name+"'"; //DbReader = DbCommand.ExecuteReader(); if (0 == System.Convert.ToInt32(DbCommand.ExecuteScalar())) return false; else return true; }
public List<CodeRecord> Load() { var rv = new List<CodeRecord>(); // load code points using ( var tx = con.BeginTransaction() ) using ( var cmd = new SqliteCommand( con ) ){ cmd.Transaction = tx; cmd.CommandText = @"SELECT fullname, assembly, sourcefile, classname, name FROM methods"; using ( var sth = cmd.ExecuteReader() ) { while ( sth.HasRows && sth.Read() ){ var rec = new CodeRecord(); rec.FullMethodName = Convert.ToString( sth["fullname"] ); rec.Assembly = Convert.ToString( sth["assembly"] ); rec.SourceFile = Convert.ToString( sth["sourcefile"] ); rec.ClassName = Convert.ToString( sth["classname"] ); rec.Name = Convert.ToString( sth["name"] ); // get call count var calls = new SqliteCommand( con ); calls.CommandText = "SELECT hits FROM calls WHERE assembly = :ASSEMBLY AND fullname = :FULLNAME"; calls.Parameters.Add( new SqliteParameter( ":ASSEMBLY", rec.Assembly ) ); calls.Parameters.Add( new SqliteParameter( ":FULLNAME", rec.FullMethodName ) ); var ccount = Convert.ToInt32( calls.ExecuteScalar() ); rec.CallCount = ccount; // get lines var lines = new SqliteCommand( con ); lines.CommandText = "SELECT line, hits FROM lines WHERE assembly = :ASSEMBLY AND fullname = :FULLNAME"; lines.Parameters.Add( new SqliteParameter( ":ASSEMBLY", rec.Assembly ) ); lines.Parameters.Add( new SqliteParameter( ":FULLNAME", rec.FullMethodName ) ); using ( var lsth = lines.ExecuteReader() ){ while ( lsth.HasRows && lsth.Read() ) { var l = Convert.ToInt32( lsth["line"] ); var hc = Convert.ToInt32( lsth["hits"] ); rec.AddLines(l); rec.SetHits( l, hc ); } } rv.Add(rec); } } tx.Commit(); } return rv; }
public static void RunTests(string dbPath) { using (var cnn = new SqliteConnection("Data Source=" + dbPath)) { cnn.Open(); // commit using (var trn = cnn.BeginTransaction(IsolationLevel.Serializable)) using (var cmd = new SqliteCommand("CREATE TABLE IF NOT EXISTS nugettest (id INTEGER PRIMARY KEY AUTOINCREMENT, data TEXT);", cnn)) { cmd.ExecuteNonQuery(); cmd.CommandText = "DELETE FROM nugettest;"; cmd.ExecuteNonQuery(); cmd.CommandText = "INSERT INTO nugettest (data) VALUES (@someData);"; cmd.Parameters.AddWithValue("@someData", "data here"); cmd.ExecuteNonQuery(); trn.Commit(); } // rollback using (var trn = cnn.BeginTransaction(IsolationLevel.Serializable)) using (var cmd = new SqliteCommand("INSERT INTO nugettest (data) VALUES (@someData);", cnn)) { cmd.Parameters.AddWithValue("@someData", "data here"); cmd.ExecuteNonQuery(); trn.Rollback(); } // check using (var cmd = new SqliteCommand("SELECT COUNT(*) nugettest;", cnn)) { if (Convert.ToInt32(cmd.ExecuteScalar()) != 1) { throw new Exception("Something bad happened!"); } } } }
//Called from initialize jump, jumpRj public static int GraphLinkInsert(string tableName, string eventName, string graphFileName, bool dbconOpened, SqliteCommand mycmd) { if(! dbconOpened) { Sqlite.Open(); } mycmd.CommandText = "INSERT INTO graphLinkTable" + "(uniqueID, tableName, eventName, graphFileName, other1, other2)" + " VALUES (NULL, \"" + tableName + "\", \"" + eventName + "\", \"" + graphFileName + "\", \"\", \"\")" ; LogB.SQL(mycmd.CommandText.ToString()); mycmd.ExecuteNonQuery(); //int myLast = dbcon.LastInsertRowId; //http://stackoverflow.com/questions/4341178/getting-the-last-insert-id-with-sqlite-net-in-c string myString = @"select last_insert_rowid()"; mycmd.CommandText = myString; int myLast = Convert.ToInt32(mycmd.ExecuteScalar()); // Need to type-cast since `ExecuteScalar` returns an object. if(! dbconOpened) { Sqlite.Close(); } return myLast; }
//////////////////////////////////////////////////////// // Get Property Values from Database // //----------------------------------------------------// private void GetPropertyValuesFromDatabase(string username, SettingsPropertyValueCollection svc) { try { SqliteConnection holder = new SqliteConnection(_connectionString); SqliteDataReader reader = null; string[] names = null; string values = null; try {//read data holder.Open(); int appId = GetApplicationId(holder); cmd = new SqliteCommand("SELECT PKID FROM Users WHERE UserName ='******'", holder); PKID = cmd.ExecuteScalar(); if (PKID != null) { // User exists? cmd = new SqliteCommand("SELECT PropertyNames, PropertyValuesString FROM aspnet_Profile WHERE PKID ='" + PKID + "'", holder); reader = cmd.ExecuteReader(); if (reader.Read()) { names = reader.GetString(0).Split(':'); values = reader.GetString(1); } /*try { // Not a critical part -- don't throw exceptions here cmd = new SqliteCommand("UPDATE users SET LastActivityDate='" + DateTime.Now.ToString("yyyy:MM:dd hh:mm:ss") + "' WHERE PKID ='" + PKID + "'", holder); cmd.ExecuteNonQuery(); } catch { }*/ } } catch (Exception e) { if (WriteExceptionsToEventLog) { WriteToEventLog(e, "Get Property From DB"); throw new ProviderException(exceptionMessage); } else { throw e; } } finally { if (reader != null) reader.Close(); holder.Close(); } if (names != null && names.Length > 0) { ParseDataFromDB(names, values, new byte[0], svc); } } catch { throw; } }
public void ScalarReturn() { // This should return the 1 line that got inserted in CreateTable() Test using (_conn) using (SqliteCommand cmd = new SqliteCommand("SELECT COUNT(*) FROM t1 WHERE t LIKE '%äöüß'", _conn)) { _conn.Open(); Assert.AreEqual(1, Convert.ToInt32(cmd.ExecuteScalar())); } }
protected void OnButtonOkClicked(object sender, EventArgs e) { string sql; if (NewItem) { sql = "INSERT INTO basis (name, width, delta_l, delta_h) " + "VALUES (@name, @width, @delta_l, @delta_h)"; } else { sql = "UPDATE basis SET name = @name, width = @width, delta_l = @delta_l, delta_h = @delta_h WHERE id = @id"; } SqliteTransaction trans = ((SqliteConnection)QSMain.ConnectionDB).BeginTransaction(); MainClass.StatusMessage("Запись основы..."); try { SqliteCommand cmd = new SqliteCommand(sql, (SqliteConnection)QSMain.ConnectionDB, trans); cmd.Parameters.AddWithValue("@id", ItemId); cmd.Parameters.AddWithValue("@name", entryName.Text); cmd.Parameters.AddWithValue("@width", spinW.ValueAsInt); cmd.Parameters.AddWithValue("@delta_l", spinL.ValueAsInt); cmd.Parameters.AddWithValue("@delta_h", spinH.ValueAsInt); cmd.ExecuteNonQuery(); if(NewItem) { sql = @"select last_insert_rowid()"; cmd = new SqliteCommand(sql, (SqliteConnection)QSMain.ConnectionDB, trans); ItemId = Convert.ToInt32(cmd.ExecuteScalar()); sql = "UPDATE basis SET ordinal = @id WHERE id = @id"; cmd = new SqliteCommand(sql, (SqliteConnection)QSMain.ConnectionDB, trans); cmd.Parameters.AddWithValue("@id", ItemId); cmd.ExecuteNonQuery(); } // Запись Номенклатур foreach(object[] nomenclature in NomenclatureStore) { if((bool) nomenclature[(int)NomenclatureCol.selected]) { if((long) nomenclature[(int)NomenclatureCol.id] > 0) sql = "UPDATE basis_items SET count = @count WHERE id = @id"; else sql = "INSERT INTO basis_items (basis_id, item_id, count) VALUES (@basis_id, @item_id, @count)"; cmd = new SqliteCommand(sql, (SqliteConnection)QSMain.ConnectionDB, trans); cmd.Parameters.AddWithValue("@basis_id", ItemId); cmd.Parameters.AddWithValue("@id", nomenclature[(int)NomenclatureCol.id]); cmd.Parameters.AddWithValue("@item_id", nomenclature[(int)NomenclatureCol.nomenclature_id]); cmd.Parameters.AddWithValue("@count", nomenclature[(int)NomenclatureCol.count]); cmd.ExecuteNonQuery(); } else if((long) nomenclature[(int)NomenclatureCol.id] > 0) { sql = "DELETE FROM basis_items WHERE basis_id = @basis_id AND item_id = @item_id"; cmd = new SqliteCommand(sql, (SqliteConnection)QSMain.ConnectionDB, trans); cmd.Parameters.AddWithValue("@basis_id", ItemId); cmd.Parameters.AddWithValue("@item_id", nomenclature[(int)NomenclatureCol.nomenclature_id]); cmd.ExecuteNonQuery(); } } if(ImageChanged) { if(NewItem) { sql = @"select last_insert_rowid()"; cmd = new SqliteCommand(sql, (SqliteConnection)QSMain.ConnectionDB, trans); ItemId = Convert.ToInt32(cmd.ExecuteScalar()); } sql = "UPDATE basis SET image_size = @image_size, image = @image WHERE id = @id"; cmd = new SqliteCommand(sql, (SqliteConnection)QSMain.ConnectionDB, trans); cmd.Parameters.AddWithValue("@id", ItemId); cmd.Parameters.AddWithValue("@image_size", ImageHelper.OriginalFile.Length); cmd.Parameters.AddWithValue("@image", ImageHelper.OriginalFile); cmd.ExecuteNonQuery(); } trans.Commit(); MainClass.StatusMessage("Ok"); Respond(Gtk.ResponseType.Ok); } catch (Exception ex) { trans.Rollback(); QSMain.ErrorMessageWithLog(this, "Ошибка записи основы!", logger, ex); } }
/// <summary> /// 执行查询语句,返回查询结果的第一行第一列 /// </summary> /// <param name="sql">查询语句</param> /// <param name="parameters">查询语句所需要的参数</param> /// <returns></returns> public string ExecuteScalar(string sql) { using (SqliteConnection connection = new SqliteConnection(dbConnectionString)) { connection.Open(); using (SqliteCommand command = new SqliteCommand(sql, connection)) { object value = command.ExecuteScalar(); return value != null ? value.ToString() : ""; } } }
/// <summary> /// Saving order information to DB. /// </summary> private bool Save() { string sql; if (NewItem) { sql = "INSERT INTO orders (customer, estimation, contract, address, phone1, phone2, exhibition_id, basis_id, " + "arrval, deadline_s, deadline_e, comment, cupboard, total_price, price_correction, cutting_base, basis_price) " + "VALUES (@customer, @estimation, @contract, @address, @phone1, @phone2, @exhibition_id, @basis_id, @arrval, " + "@deadline_s, @deadline_e, @comment, @cupboard, @total_price, @price_correction, @cutting_base, @basis_price)"; } else { sql = "UPDATE orders SET customer = @customer, estimation = @estimation, contract = @contract, address = @address, " + "phone1 = @phone1, phone2 = @phone2, exhibition_id = @exhibition_id, basis_id = @basis_id, arrval = @arrval, " + "deadline_s = @deadline_s, deadline_e = @deadline_e, comment = @comment, cupboard = @cupboard, " + "total_price = @total_price, price_correction = @price_correction, cutting_base = @cutting_base, basis_price = @basis_price WHERE id = @id"; } SqliteTransaction trans = ((SqliteConnection)QSMain.ConnectionDB).BeginTransaction(); MainClass.StatusMessage("Запись заказа..."); try { int contract; SqliteCommand cmd = new SqliteCommand(sql, (SqliteConnection)QSMain.ConnectionDB, trans); cmd.Parameters.AddWithValue("@id", ItemId); cmd.Parameters.AddWithValue("@customer", DBWorks.ValueOrNull(entryCustomer.Text != "", entryCustomer.Text)); cmd.Parameters.AddWithValue("@estimation", checkEstimation.Active); cmd.Parameters.AddWithValue("@contract", DBWorks.ValueOrNull(int.TryParse(entryContract.Text, out contract), contract)); cmd.Parameters.AddWithValue("@address", DBWorks.ValueOrNull(textAddress.Buffer.Text != "", textAddress.Buffer.Text)); cmd.Parameters.AddWithValue("@phone1", DBWorks.ValueOrNull(entryPhone1.Text != "", entryPhone1.Text)); cmd.Parameters.AddWithValue("@phone2", DBWorks.ValueOrNull(entryPhone2.Text != "", entryPhone2.Text)); cmd.Parameters.AddWithValue("@arrval", DBWorks.ValueOrNull(!dateArrval.IsEmpty, dateArrval.Date)); cmd.Parameters.AddWithValue("@deadline_s", DBWorks.ValueOrNull(!dateDeadlineS.IsEmpty, dateDeadlineS.Date)); cmd.Parameters.AddWithValue("@deadline_e", DBWorks.ValueOrNull(!dateDeadlineE.IsEmpty, dateDeadlineE.Date)); CupboardListItem basis = TypeWidgetList.Find(w => w.Button.Active); cmd.Parameters.AddWithValue("basis_id", DBWorks.ValueOrNull(basis != null, basis.id)); cmd.Parameters.AddWithValue("basis_price", ComponentsStore.GetValue(BasisIter, (int)ComponentCol.price_total)); cmd.Parameters.AddWithValue("exhibition_id", ComboWorks.GetActiveIdOrNull(comboExhibition)); cmd.Parameters.AddWithValue("@comment", DBWorks.ValueOrNull(textviewComments.Buffer.Text != "", textviewComments.Buffer.Text)); cmd.Parameters.AddWithValue("@cupboard", OrderCupboard.SaveToString()); cmd.Parameters.AddWithValue("@total_price", TotalPrice); cmd.Parameters.AddWithValue("@price_correction", PriceCorrection); cmd.Parameters.AddWithValue("@cutting_base", checkCuttingBase.Active); cmd.ExecuteNonQuery(); if(NewItem) { sql = @"select last_insert_rowid()"; cmd = new SqliteCommand(sql, (SqliteConnection)QSMain.ConnectionDB, trans); ItemId = Convert.ToInt32(cmd.ExecuteScalar()); NewItem = false; } // Saving components // Saving services TreeIter iter, childIter; if(ComponentsStore.IterHasChild(ServiceIter)) { ComponentsStore.IterChildren(out childIter, ServiceIter); do { bool InDB = (long)ComponentsStore.GetValue(childIter, (int)ComponentCol.row_id) > 0; if(!InDB) sql = "INSERT INTO order_services (order_id, name, price, discount, comment) " + "VALUES (@order_id, @name, @price, @discount, @comment)"; else sql = "UPDATE order_services " + "SET name = @name, price = @price, discount = @discount, comment = @comment " + "WHERE id = @id"; cmd = new SqliteCommand(sql, (SqliteConnection)QSMain.ConnectionDB, trans); cmd.Parameters.AddWithValue("@id", (long)ComponentsStore.GetValue(childIter, (int)ComponentCol.row_id)); cmd.Parameters.AddWithValue("@order_id", ItemId); cmd.Parameters.AddWithValue("@name", (string)ComponentsStore.GetValue(childIter,(int)ComponentCol.nomenclature_title)); cmd.Parameters.AddWithValue("@price", ComponentsStore.GetValue(childIter,(int)ComponentCol.price)); cmd.Parameters.AddWithValue("@discount", (int)ComponentsStore.GetValue(childIter, (int)ComponentCol.discount)); cmd.Parameters.AddWithValue("@comment", (string)ComponentsStore.GetValue(childIter, (int)ComponentCol.comment)); cmd.ExecuteNonQuery(); if(!InDB) { sql = @"select last_insert_rowid()"; cmd = new SqliteCommand(sql, (SqliteConnection)QSMain.ConnectionDB, trans); long RowId = (long) cmd.ExecuteScalar(); ComponentsStore.SetValue(childIter, (int)ComponentCol.row_id, (object)RowId); } } while (ComponentsStore.IterNext(ref childIter)); childIter = new TreeIter(); } if(ComponentsStore.GetIterFirst(out iter)) { do { //If item is cube if ((Nomenclature.NomType)ComponentsStore.GetValue(iter, (int)ComponentCol.nomenclature_type) == Nomenclature.NomType.other) continue; if ((Nomenclature.NomType)ComponentsStore.GetValue(iter, (int)ComponentCol.nomenclature_type) == Nomenclature.NomType.cube) { //Writing common cube info to order_details bool HasValue = (int) ComponentsStore.GetValue(iter, (int)ComponentCol.count) > 0; bool InDB = (long)ComponentsStore.GetValue(iter, (int)ComponentCol.row_id) > 0; if(HasValue) { if(!InDB) sql = "INSERT INTO order_details (order_id, cube_id, count, facing_id, material_id, comment, price) " + "VALUES (@order_id, @nomenclature_id, @count, @facing_id, @material_id, @comment, @price)"; else sql = "UPDATE order_details SET count = @count, facing_id = @facing_id, " + "material_id = @material_id, comment = @comment, price = @price WHERE id = @id"; cmd = new SqliteCommand(sql, (SqliteConnection)QSMain.ConnectionDB, trans); cmd.Parameters.AddWithValue("@id", (long)ComponentsStore.GetValue(iter, (int)ComponentCol.row_id)); cmd.Parameters.AddWithValue("@order_id", ItemId); cmd.Parameters.AddWithValue("@nomenclature_id", ComponentsStore.GetValue(iter,(int)ComponentCol.nomenclature_id)); cmd.Parameters.AddWithValue("@count", ComponentsStore.GetValue(iter,(int)ComponentCol.count)); cmd.Parameters.AddWithValue("@material_id", DBWorks.ValueOrNull((int)ComponentsStore.GetValue(iter,(int)ComponentCol.material_id) > 0, ComponentsStore.GetValue(iter, (int)ComponentCol.material_id))); cmd.Parameters.AddWithValue("@facing_id", DBWorks.ValueOrNull((int)ComponentsStore.GetValue(iter, (int)ComponentCol.facing_id) > 0, ComponentsStore.GetValue(iter, (int)ComponentCol.facing_id))); cmd.Parameters.AddWithValue("@comment", DBWorks.ValueOrNull((string)ComponentsStore.GetValue(iter, (int)ComponentCol.comment) != "", ComponentsStore.GetValue(iter, (int)ComponentCol.comment))); cmd.Parameters.AddWithValue("@price", ComponentsStore.GetValue(iter, (int)ComponentCol.price_total)); cmd.ExecuteNonQuery(); if(!InDB) { sql = @"select last_insert_rowid()"; cmd = new SqliteCommand(sql, (SqliteConnection)QSMain.ConnectionDB, trans); long RowId = (long) cmd.ExecuteScalar(); ComponentsStore.SetValue(iter, (int)ComponentCol.row_id, (object)RowId); } } else if(InDB) { sql = "DELETE FROM order_details WHERE id = @id"; cmd = new SqliteCommand(sql, (SqliteConnection)QSMain.ConnectionDB, trans); cmd.Parameters.AddWithValue("@id", ComponentsStore.GetValue(iter, (int)ComponentCol.row_id)); cmd.ExecuteNonQuery(); } if(ComponentsStore.IterHasChild(iter)) { ComponentsStore.IterChildren(out childIter, iter); do { //Adding every nomenclature for cube HasValue = (int) ComponentsStore.GetValue(childIter, (int)ComponentCol.count) > 0; InDB = (long)ComponentsStore.GetValue(childIter, (int)ComponentCol.row_id) > 0; if(HasValue) { if(!InDB) sql = "INSERT INTO order_cubes_details (order_id, cube_id, nomenclature_id, count, price, comment, " + "discount) VALUES (@order_id, @cube_id, @nomenclature_id, @count, @price, @comment, @discount)"; else sql = "UPDATE order_cubes_details " + "SET count = @count, price = @price, comment = @comment, discount = @discount WHERE id = @id"; cmd = new SqliteCommand(sql, (SqliteConnection)QSMain.ConnectionDB, trans); cmd.Parameters.AddWithValue("@id", (long)ComponentsStore.GetValue(childIter, (int)ComponentCol.row_id)); cmd.Parameters.AddWithValue("@order_id", ItemId); cmd.Parameters.AddWithValue("@cube_id", ComponentsStore.GetValue(iter, (int)ComponentCol.nomenclature_id)); cmd.Parameters.AddWithValue("@nomenclature_id", ComponentsStore.GetValue(childIter,(int)ComponentCol.nomenclature_id)); cmd.Parameters.AddWithValue("@count", ComponentsStore.GetValue(childIter,(int)ComponentCol.count)); cmd.Parameters.AddWithValue("@price", ComponentsStore.GetValue(childIter, (int)ComponentCol.price)); cmd.Parameters.AddWithValue("@comment", DBWorks.ValueOrNull((string)ComponentsStore.GetValue(childIter, (int)ComponentCol.comment) != "", ComponentsStore.GetValue(childIter, (int)ComponentCol.comment))); cmd.Parameters.AddWithValue("@discount", ComponentsStore.GetValue(childIter, (int)ComponentCol.discount)); cmd.ExecuteNonQuery(); if(!InDB) { sql = @"select last_insert_rowid()"; cmd = new SqliteCommand(sql, (SqliteConnection)QSMain.ConnectionDB, trans); long RowId = (long) cmd.ExecuteScalar(); ComponentsStore.SetValue(childIter, (int)ComponentCol.row_id, (object)RowId); } } else if(InDB) { sql = "DELETE FROM order_cubes_details WHERE id = @id"; cmd = new SqliteCommand(sql, (SqliteConnection)QSMain.ConnectionDB, trans); cmd.Parameters.AddWithValue("@id", ComponentsStore.GetValue(childIter, (int)ComponentCol.row_id)); cmd.ExecuteNonQuery(); } } while (ComponentsStore.IterNext(ref childIter)); } } else { //Item is basis if(ComponentsStore.IterHasChild(iter)) { ComponentsStore.IterChildren(out childIter, iter); do { //Adding every nomenclature for basis bool HasValue = (int) ComponentsStore.GetValue(childIter, (int)ComponentCol.count) > 0; bool InDB = (long)ComponentsStore.GetValue(childIter, (int)ComponentCol.row_id) > 0; if(HasValue) { if(!InDB) sql = "INSERT INTO order_basis_details " + "(order_id, nomenclature_id, count, price, comment, discount, facing_id, material_id) " + "VALUES (@order_id, @nomenclature_id, @count, @price, @comment, @discount, @facing_id, @material_id)"; else sql = "UPDATE order_basis_details SET count = @count, price = @price, comment = @comment, " + "discount = @discount, facing_id = @facing_id, material_id = @material_id WHERE id = @id"; cmd = new SqliteCommand(sql, (SqliteConnection)QSMain.ConnectionDB, trans); cmd.Parameters.AddWithValue("@id", (long)ComponentsStore.GetValue(childIter, (int)ComponentCol.row_id)); cmd.Parameters.AddWithValue("@order_id", ItemId); cmd.Parameters.AddWithValue("@nomenclature_id", ComponentsStore.GetValue(childIter,(int)ComponentCol.nomenclature_id)); cmd.Parameters.AddWithValue("@count", ComponentsStore.GetValue(childIter,(int)ComponentCol.count)); cmd.Parameters.AddWithValue("@price", ComponentsStore.GetValue(childIter, (int)ComponentCol.price)); cmd.Parameters.AddWithValue("@comment", DBWorks.ValueOrNull((string)ComponentsStore.GetValue(childIter, (int)ComponentCol.comment) != "", ComponentsStore.GetValue(childIter, (int)ComponentCol.comment))); cmd.Parameters.AddWithValue("@discount", ComponentsStore.GetValue(childIter, (int)ComponentCol.discount)); cmd.Parameters.AddWithValue("@facing_id", ComponentsStore.GetValue(childIter, (int)ComponentCol.facing_id)); cmd.Parameters.AddWithValue("@material_id", ComponentsStore.GetValue(childIter, (int)ComponentCol.material_id)); cmd.ExecuteNonQuery(); if(!InDB) { sql = @"select last_insert_rowid()"; cmd = new SqliteCommand(sql, (SqliteConnection)QSMain.ConnectionDB, trans); long RowId = (long) cmd.ExecuteScalar(); ComponentsStore.SetValue(childIter, (int)ComponentCol.row_id, (object)RowId); } } else if(InDB) { sql = "DELETE FROM order_basis_details WHERE id = @id"; cmd = new SqliteCommand(sql, (SqliteConnection)QSMain.ConnectionDB, trans); cmd.Parameters.AddWithValue("@id", ComponentsStore.GetValue(childIter, (int)ComponentCol.row_id)); cmd.ExecuteNonQuery(); } } while (ComponentsStore.IterNext(ref childIter)); } } } while (ComponentsStore.IterNext(ref iter)); } trans.Commit(); MainClass.StatusMessage("Ok"); MainClass.MainWin.UpdateOrders(); return true; } catch (Exception ex) { trans.Rollback(); QSMain.ErrorMessageWithLog(this, "Ошибка записи заказа!", logger, ex); return false; } }
/// <summary> /// Saves the slide /// </summary> public void Save() { bool isInsert = false; string query = string.Empty; if (this.SlideID == null) { isInsert = true; query = @"INSERT INTO kk_slide (slide_text, slide_index, photo_id) VALUES kk_slide (@slide_text, @slide_index, @photo_id); SELECT last_insert_rowid() FROM kk_slide;"; } else { query = @"UPDATE kk_slide SET slide_text = @slide_text, slide_index = @slide_index, photo_id = @photo_id WHERE slide_id = @slide_id;"; } using (SqliteConnection conn = new SqliteConnection(connectionString)) { conn.Open(); // execute cmd using (SqliteCommand cmd = new SqliteCommand(query, conn)) { cmd.Parameters.Add("@slide_text", System.Data.DbType.String).Value = this.SlideText; cmd.Parameters.Add("@slide_index", System.Data.DbType.Int32).Value = this.SlideIndex; cmd.Parameters.Add("@photo_id", System.Data.DbType.Int32).Value = this.PhotoID; if (isInsert) { this.SlideID = Convert.ToInt32(cmd.ExecuteScalar()); } else { cmd.Parameters.Add("@slide_id", System.Data.DbType.Int32).Value = this.SlideID; cmd.ExecuteNonQuery(); } } } }
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; }
public string GetFilepath(string hash) { using (SqliteCommand sqc = new SqliteCommand(connection)) { sqc.CommandText = "SELECT path FROM Files WHERE hash=:hash"; sqc.Parameters.Add(new SqliteParameter("hash", hash)); object result = sqc.ExecuteScalar(); return (result == null) ? null : (string)result; } }
public string GetEmailByCustomerNumber(string num) { string output = ""; try { using (SqliteConnection connection = new SqliteConnection(_connectionString)) { connection.Open(); string sql = "select email from CustomerLogin where customerNumber = " + num; SqliteCommand cmd = new SqliteCommand(sql, connection); output = (string)cmd.ExecuteScalar(); } } catch (Exception ex) { log.Error("Error getting email by customer number", ex); output = ex.Message; } return output; }
// // MembershipProvider.GetAllUsers // public override MembershipUserCollection GetAllUsers(int pageIndex, int pageSize, out int totalRecords) { SqliteConnection conn = new SqliteConnection(connectionString); SqliteCommand cmd = new SqliteCommand("SELECT Count(*) FROM `" + tableName + "` " + "WHERE ApplicationName = $ApplicationName", conn); cmd.Parameters.Add("$ApplicationName", DbType.String, 255).Value = ApplicationName; MembershipUserCollection users = new MembershipUserCollection(); SqliteDataReader reader = null; totalRecords = 0; try { conn.Open(); totalRecords = Convert.ToInt32(cmd.ExecuteScalar()); if (totalRecords <= 0) { return users; } cmd.CommandText = "SELECT PKID, Username, Email, PasswordQuestion," + " Comment, IsApproved, IsLockedOut, CreationDate, LastLoginDate," + " LastActivityDate, LastPasswordChangedDate, LastLockedOutDate " + " FROM `" + tableName + "` " + " WHERE ApplicationName = $ApplicationName " + " ORDER BY Username Asc"; reader = cmd.ExecuteReader(); int counter = 0; int startIndex = pageSize * pageIndex; int endIndex = startIndex + pageSize - 1; while (reader.Read()) { if (counter >= startIndex) { MembershipUser u = GetUserFromReader(reader); users.Add(u); } if (counter >= endIndex) { cmd.Cancel(); } counter++; } } catch (SqliteException e) { if (WriteExceptionsToEventLog) { WriteToEventLog(e, "GetAllUsers"); throw new ProviderException(exceptionMessage); } else { throw e; } } finally { if (reader != null) { reader.Close(); } conn.Close(); } return users; }
/// <summary> /// Returns the current sequence value for the given Sequence from the DB. /// </summary> /// <param name="ASequenceName">Name of the Sequence.</param> /// <param name="ATransaction">An instantiated Transaction in which the Query /// to the DB will be enlisted.</param> /// <param name="ADatabase">Database object that can be used for querying.</param> /// <returns>Sequence Value.</returns> public System.Int64 GetCurrentSequenceValue(String ASequenceName, TDBTransaction ATransaction, TDataBase ADatabase) { string stmt = "SELECT MAX(sequence) FROM " + ASequenceName + ";"; using (SqliteCommand cmd = new SqliteCommand(stmt, (SqliteConnection)ATransaction.Connection)) { return Convert.ToInt64(cmd.ExecuteScalar()); } }
void NoteCollectionRepo.AddNew(ITaskCore container, INoteCore item) { var command = "INSERT INTO Notes (Name, Text, Task)" + "VALUES (@name, @text, @id); SELECT last_insert_rowid();"; using (var cmd = new SqliteCommand (database.Connection)) { cmd.CommandText = command; cmd.Parameters.AddWithValue ("@name", item.Title); cmd.Parameters.AddWithValue ("@text", item.Text); cmd.Parameters.AddIdParameter (container); var id = cmd.ExecuteScalar ().ToString (); item.SetId (id); } }
// // MembershipProvider.GetNumberOfUsersOnline // public override int GetNumberOfUsersOnline() { TimeSpan onlineSpan = new TimeSpan(0, System.Web.Security.Membership.UserIsOnlineTimeWindow, 0); DateTime compareTime = DateTime.Now.Subtract(onlineSpan); SqliteConnection conn = new SqliteConnection(connectionString); SqliteCommand cmd = new SqliteCommand("SELECT Count(*) FROM `" + tableName + "`" + " WHERE LastActivityDate > $LastActivityDate AND ApplicationName = $ApplicationName", conn); cmd.Parameters.Add("$CompareDate", DbType.DateTime).Value = compareTime; cmd.Parameters.Add("$ApplicationName", DbType.String, 255).Value = pApplicationName; int numOnline = 0; try { conn.Open(); numOnline = Convert.ToInt32(cmd.ExecuteScalar()); } catch (SqliteException e) { if (WriteExceptionsToEventLog) { WriteToEventLog(e, "GetNumberOfUsersOnline"); throw new ProviderException(exceptionMessage); } else { throw e; } } finally { conn.Close(); } return numOnline; }
public int AddTask(TaskItem task) { using (var conn = new SqliteConnection(connectionString)) using (var cmd = new SqliteCommand(@" INSERT INTO [Tasks] ( [Name], [IsComplete] ) VALUES ( @name, @complete ); SELECT last_insert_rowid();", conn)) { cmd.Parameters.AddWithValue("@name", task.Name); cmd.Parameters.AddWithValue("@complete", task.IsComplete); conn.Open(); using (var trans = new TransactionScope(TransactionScopeOption.Required, new TransactionOptions {IsolationLevel = IsolationLevel.Serializable})) { var result = cmd.ExecuteScalar(); trans.Complete(); return Convert.ToInt32(result); } } }
// // MembershipProvider.GetUserNameByEmail // public override string GetUserNameByEmail(string email) { SqliteConnection conn = new SqliteConnection(connectionString); SqliteCommand cmd = new SqliteCommand("SELECT Username" + " FROM `" + tableName + "` WHERE Email = $Email AND ApplicationName = $ApplicationName", conn); cmd.Parameters.Add("$Email", DbType.String, 128).Value = email; cmd.Parameters.Add("$ApplicationName", DbType.String, 255).Value = pApplicationName; string username = ""; try { conn.Open(); object o = cmd.ExecuteScalar(); if (o != null) username = Convert.ToString(o); } catch (SqliteException e) { if (WriteExceptionsToEventLog) { WriteToEventLog(e, "GetUserNameByEmail"); throw new ProviderException(exceptionMessage); } else { throw e; } } finally { conn.Close(); } if (username == null) username = ""; return username; }
/// <summary> /// Saves the Project /// </summary> public void Save() { bool isInsert = false; string query = string.Empty; if (this.ProjectID == null) { isInsert = true; query = @"INSERT INTO kk_project (project_name, project_description, project_html, project_added_by, project_photo_id, parent_id) VALUES (@project_name, @project_description, @project_html, @project_added_by, @project_photo_id, @parent_id); SELECT last_insert_rowid() FROM kk_photo; "; } else { query = @"UPDATE kk_project SET project_name = @project_name, project_description = @project_description, project_html = @project_html, project_photo_id = @project_photo_id, parent_id = @parent_id WHERE project_id = @project_id;"; } using (SqliteConnection conn = new SqliteConnection(connectionString)) { conn.Open(); // execute cmd using (SqliteCommand cmd = new SqliteCommand(query, conn)) { cmd.Parameters.Add("@project_name", System.Data.DbType.String).Value = this.ProjectName; if (this.ProjectDescription != string.Empty) cmd.Parameters.Add("@project_description", System.Data.DbType.String).Value = this.ProjectDescription; else cmd.Parameters.Add("@project_description", System.Data.DbType.String).Value = DBNull.Value; cmd.Parameters.Add("@project_html", System.Data.DbType.String).Value = this.ProjectHtml; cmd.Parameters.Add("@project_photo_id", System.Data.DbType.Int32).Value = this.ProjectImageID; if (this.ParentID != null) { cmd.Parameters.Add ("@parent_id", System.Data.DbType.Int32).Value = this.ParentID; } else { cmd.Parameters.Add ("@parent_id", System.Data.DbType.Int32).Value = DBNull.Value; } if (isInsert) { cmd.Parameters.Add("@project_added_by", System.Data.DbType.Int32).Value = this.ProjectAddedById; this.ProjectID = Convert.ToInt32(cmd.ExecuteScalar()); } else { cmd.Parameters.Add("@project_id", System.Data.DbType.Int32).Value = this.ProjectID; cmd.ExecuteNonQuery(); } } } }
public object ExecuteScalar(string sql) { using (SqliteConnection conn = new SqliteConnection(this.SqlConfig.ConnectionString)) { using (SqliteCommand cmd = new SqliteCommand()) { try { conn.Open(); cmd.Connection = conn; object o = null; cmd.CommandText = sql; o = cmd.ExecuteScalar(); return o; } catch { conn.Close(); throw; } finally { conn.Close(); } } } }
void CopyDatabase(SqliteConnection src) { Console.WriteLine ("Migrating ironpython completion database to version {0}", s_version); int batchSize = 100; var cmd = new SqliteCommand ("SELECT " + s_ItemColumns + " FROM Items;", src); var reader = cmd.ExecuteReader (); int i = 0; var items = new List<ParserItem> (); var rowsCommand = new SqliteCommand ("SELECT count(*) FROM Items;", src); var count = (long)rowsCommand.ExecuteScalar (); var progress = IdeApp.Workbench.ProgressMonitors.GetBackgroundProgressMonitor ("IronPython Completion Database", Gtk.Stock.Execute); progress.BeginTask ("Migrating completion database", (int)count); while (reader.Read ()) { var item = new ParserItem (); item.Deserialize (reader); items.Add (item); i++; if (i % batchSize == 0) { AddRange (items); progress.Step (items.Count); items.Clear (); } } if (items.Count > 0) AddRange (items); progress.Step (items.Count); items.Clear (); progress.Dispose (); }
//////////////////////////////////////////////////////// // Set Property Values // //----------------------------------------------------// public override void SetPropertyValues(SettingsContext sc, SettingsPropertyValueCollection properties) { try { string username = (string)sc["UserName"]; bool userIsAuthenticated = (bool)sc["IsAuthenticated"]; if (username == null || username.Length < 1 || properties.Count < 1) return; string names = String.Empty; string values = String.Empty; byte[] buf = null; PrepareDataForSaving(ref names, ref values, ref buf, false, properties, userIsAuthenticated); if (names.Length == 0) return; SqliteConnection conn = new SqliteConnection(_connectionString); SqliteTransaction trans = null; bool fBeginTransCalled = false; try {//Store Data conn.Open(); trans = conn.BeginTransaction(); fBeginTransCalled = true; cmd = new SqliteCommand("SELECT PKID FROM Users WHERE UserName = '******'", conn, trans); PKID = cmd.ExecuteScalar(); cmd = new SqliteCommand("SELECT PKID FROM aspnet_Profile WHERE PKID = '" + PKID + "'", conn, trans); object result = cmd.ExecuteScalar(); string PKID1 = Convert.ToString(result); string PKID2 = PKID.ToString(); if (result != null && (PKID1 == PKID2)) { cmd = new SqliteCommand("UPDATE aspnet_Profile SET PropertyNames ='" + names + "', PropertyValuesString ='" + values + "', LastUpdatedDate ='" + DateTime.Now.ToString("yyyy:MM:dd hh:mm:ss") + "' WHERE PKID ='" + PKID + "'", conn, trans); } else { cmd = new SqliteCommand("INSERT INTO aspnet_Profile (PKID, PropertyNames, PropertyValuesString, LastUpdatedDate) VALUES ('" + PKID + "','" + names + "','" + values + "','" + DateTime.Now.ToString("yyyy:MM:dd hh:mm:ss") + "')", conn, trans); } cmd.ExecuteNonQuery(); try { // Not a critical part -- don't throw exceptions here cmd = new SqliteCommand("UPDATE users SET LastActivityDate='" + DateTime.Now.ToString("yyyy:MM:dd hh:mm:ss") + "' WHERE PKID = '" + PKID + "'", conn); cmd.ExecuteNonQuery(); } catch { } trans.Commit(); fBeginTransCalled = false; } catch (Exception e) { trans.Rollback(); if (WriteExceptionsToEventLog) { WriteToEventLog(e, "Error Setting Property"); throw new ProviderException(exceptionMessage); } else { throw e; } } finally { if (fBeginTransCalled) { try { trans.Rollback(); } catch { } } conn.Close(); } } catch { throw; } }
/// <summary> /// Converts a posted http image to a C# System.Drawing.Image /// </summary> /// <param name="postedImage">HttpPostedFileBase</param> /// <returns>System.Drawing.Image</returns> public void Save() { string query = string.Empty; bool isUpdate = false; if (this.PhotoID != null) { query = @"UPDATE kk_photo SET photo_name = @photo_name, photo_raw = @photo_raw, photo_large = @photo_large, photo_medium = @photo_medium, photo_small = @photo_small, photo_thumb = @photo_thumb, photo_width = @photo_width, photo_height = @photo_height WHERE photo_id = @photo_id; "; isUpdate = true; } else { query = @"INSERT INTO kk_photo (photo_name, photo_raw, photo_large, photo_medium, photo_small, photo_thumb, photo_width, photo_height) VALUES (@photo_name, @photo_raw, @photo_large, @photo_medium, @photo_small, @photo_thumb, @photo_width, @photo_height); SELECT last_insert_rowid() FROM kk_photo; "; } using (SqliteConnection conn = new SqliteConnection(connectionString)) { conn.Open(); // execute cmd using (SqliteCommand cmd = new SqliteCommand(query, conn)) { cmd.Parameters.Add("@photo_name", System.Data.DbType.String).Value = this.PhotoName; cmd.Parameters.Add("@photo_raw", System.Data.DbType.Binary).Value = this.PhotoRawData; cmd.Parameters.Add("@photo_large", System.Data.DbType.Binary).Value = this.PhotoLargeData; cmd.Parameters.Add("@photo_medium", System.Data.DbType.Binary).Value = this.PhotoMediumData; cmd.Parameters.Add("@photo_small", System.Data.DbType.Binary).Value = this.PhotoSmallData; cmd.Parameters.Add("@photo_thumb", System.Data.DbType.Binary).Value = this.PhotoThumbData; cmd.Parameters.Add("@photo_width", System.Data.DbType.Int32).Value = this.PhotoWidth; cmd.Parameters.Add("@photo_height", System.Data.DbType.Int32).Value = this.PhotoHeight; if (isUpdate) { cmd.Parameters.Add("@photo_id", System.Data.DbType.Int32).Value = this.PhotoID; cmd.ExecuteNonQuery(); } else { this.PhotoID = Convert.ToInt32(cmd.ExecuteScalar()); } } } }
//////////////////////////////////////////////////////// // Delete Profile // //----------------------------------------------------// private bool DeleteProfile(SqliteConnection holder, string username, int appId) { //SecUtility.CheckParameter(ref username, true, true, true, 255, "username"); holder.Open(); cmd = new SqliteCommand("SELECT PKID FROM Users WHERE UserName ='******'", holder); PKID = cmd.ExecuteScalar(); if (PKID.ToString() == "0") return false; cmd = new SqliteCommand("DELETE FROM aspnet_Profile WHERE PKID ='" + PKID + "'", holder); bool Result; Result = cmd.ExecuteNonQuery() != 0; holder.Close(); return (Result); }
void TaskListTaskCollectionRepo.AddNew (ITaskListCore container, ITaskCore item) { var command = "INSERT INTO Tasks" + "(Name, DueDate, CompletionDate, Priority, State, " + "Category, ExternalID) " + "VALUES (@name, @dueDate, @completionDate, " + "@priority, @state, @catId, ''); " + "SELECT last_insert_rowid();"; using (var cmd = new SqliteCommand (database.Connection)) { cmd.CommandText = command; cmd.Parameters.AddWithValue ("@name", item.Text); cmd.Parameters.AddWithValue ("@dueDate", Database.FromDateTime (item.DueDate)); cmd.Parameters.AddWithValue ("@completionDate", Database.FromDateTime (DateTime.MinValue)); cmd.Parameters.AddWithValue ("@priority", (int)item.Priority); cmd.Parameters.AddWithValue ("@state", (int)item.State); cmd.Parameters.AddWithValue ("@catId", int.Parse (container.Id)); var id = cmd.ExecuteScalar ().ToString (); item.SetId (id); } }
//////////////////////////////////////////////////////// // Get Application Id // //----------------------------------------------------// private int GetApplicationId(SqliteConnection holder) { if (_ApplicationId != 0) // Already cached? return _ApplicationId; string appName = _AppName; if (appName.Length > 255) appName = appName.Substring(0, 255); try { cmd = new SqliteCommand("SELECT ApplicationId FROM aspnet_applications WHERE ApplicationName = '" + appName + "'", holder); _ApplicationId = (Convert.ToInt32(cmd.ExecuteScalar())); _ApplicationIDCacheDate = DateTime.Now; if (_ApplicationId >= 0) return _ApplicationId; throw new ProviderException("Could not get ApplicationId"); } catch (Exception e) { if (WriteExceptionsToEventLog) { WriteToEventLog(e, "Error Getting AppId"); throw new ProviderException(exceptionMessage); } else { throw e; } } }