-
MY PROJECTS
-
Recent Posts
- SQL.How can you compare two nullable values safely, and how does IS DISTINCT FROM differ from <>?
- SQL.How are NULL values ordered by ORDER BY, how do defaults differ between databases, and how can you control their placement?
- SQL.How does NULL propagate through arithmetic expressions, and how can COALESCE and NULLIF help handle missing values and division by zero?
- SQL.How does NULL affect join conditions, and why can filtering the right-hand table in WHERE remove unmatched rows from a LEFT JOIN?
- SQL.How do GROUP BY and DISTINCT treat NULL values, even though NULL = NULL evaluates to UNKNOWN?
- SQL.How do aggregate functions handle NULL, and what is the difference between COUNT(*), COUNT(column), and COUNT(DISTINCT column)?
- SQL.How does NULL affect IN and NOT IN, and why can NOT EXISTS be a safer choice when a subquery returns nullable values?
- SQL.How do WHERE, HAVING, and CHECK constraints treat conditions that evaluate to UNKNOWN?
- SQL.Why do column = NULL and column <> NULL not work as expected, and when should you use IS NULL and IS NOT NULL?
- SQL.What is SQL’s three-valued logic (TRUE, FALSE, UNKNOWN), and how do AND, OR, and NOT behave with UNKNOWN?
- ChromeDevTools.Watch all failed requests
- SQL.What are domain types (or constraints on data types), and how do they help enforce data correctness?
- SQL.How does SQL handle comparisons between different data types (for example, string vs number), and why is this dangerous?
- SQL.What is the difference between DATE, TIME, TIMESTAMP, and TIMESTAMPTZ, and which one should be used for business events?
- SQL.How do numeric types like INTEGER, BIGINT, DECIMAL, and FLOAT differ in terms of precision and use cases?
- SQL.What problems can arise from implicit type casting in SQL, and how can it affect indexes?
- SQL.How does NULL differ from 0, an empty string, or FALSE in SQL?
- SQL.What is the difference between CHAR, VARCHAR, and TEXT, and when would you choose each?
- SQL.What is MVCC ?
- SQL.What is AutoVacuum Postgres ?
Categories
- Aptana
- Azure
- C#
- DataSnap
- DBExpress
- Delphi
- Delphi и сети
- Delphi. Язык программирования
- ExtJS
- FastReport
- FireDAC
- FireMonkey
- GIT
- ICS
- IDE
- IIS
- Indy
- InnoSetup
- javascript
- jQuery
- JSON
- LiveBindings
- MSHTML
- MySQL
- PHP
- REST
- Ribbons
- SMS
- SQL инструкции
- SVN
- TRichView
- UniGui
- WebBroker
- WinAPI
- Windows
- Алгоритмы
- Без рубрики
- Деревья
- Ищу ответ
- Компонентостроение
- Мои компоненты
- Начальный уровень
- Обработка исключений
- Парсинг
- Потоки(Threads)
- Регулярные выражения
- Тестирование приложений
Category Archives: C#
C#. Out params of queries
Параметры, которые используются в командах, могут быть нескольких типов. Тип параметра задается с помощью свойства Direction объкта SqlParameter. Данное свойство принимает одно из значений перечисления ParameterDirection: Input: параметр является входным, то есть предназначен для передачи значений в sql-выражение запроса. Это значение по умолчанию … Continue reading
Posted in C#
Comments Off on C#. Out params of queries
С#. Queries with params
Ранее для отправки запросов мы напрямую добавляли данные в выражение sql. Например, для отправки запроса на добавление данных в БД применялось следующее выражение:
|
1 |
string sqlExpression = String.Format("INSERT INTO Users (Name, Age) VALUES ('{0}', {1})", name, age); |
В данном случае предполагается, что значения для переменных name и age вводит пользователь. Что если переменная … Continue reading
Posted in C#
Comments Off on С#. Queries with params
С#. ADO.NET. Getting scalar values from DB
Metanit При отправке запросов мы можем использовать специальные встроенные функции SQL, например, Min, Max, Sum, Count и т.д., которые не выполняют операции с объектами и не извлекают объекты, а возвращают какое-то определенное значение. Например, функция Count подсчитывает количество объектов. И … Continue reading
Posted in C#
Comments Off on С#. ADO.NET. Getting scalar values from DB
C#. ADO.NET. SqlDataReader
Metanit В прошлой теме мы рассмотрели, как выполнять команды с помощью метода ExecuteNonOuery(), однако если мы хотим считывать данные, которые хранятся в таблице, то нам потребуется другой метод – ExecuteReader(). Этот метод возвращает объект SqlDataReader, который используется для чтения данных. Так, получим все … Continue reading
Posted in C#
Comments Off on C#. ADO.NET. SqlDataReader
С#. SQLNonQuery Execute
Metanit После установки подключения мы можем выполнить к базе данных какие-либо команды, например, добавить в базу данных объект, удалить, изменить его или просто извлечь. Команды представлены объектом интерфейса System.Data.IDbCommand. Провайдер для MS SQL предоставляет его реализацию в виде класса SqlCommand. Этот … Continue reading
Posted in C#
Comments Off on С#. SQLNonQuery Execute
C#. ADO.NET. Connection pool
Metanit Как правило, в программе используется одна или несколько одних и тех же конфигураций подключений. И чтобы разработчику не приходилось создавать по нескольку раз в коде программы фактически одно и тоже подключение, в ADO.NET используется механизм пула подключений. К тому же … Continue reading
Posted in C#
Comments Off on C#. ADO.NET. Connection pool
C#. ADO.Net. Connection
Source metanit Example shows connection with MSSQLServer -connection with try/finally -connection with using -connection with async / await
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 |
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Configuration; using System.Data.SqlClient; namespace sqlServer { class Program { static void Main(string[] args) { //string connectionString = @"Data Source=.\SQLEXPRESS01;Initial Catalog=usersdb;Integrated Security=True"; // получаем строку подключения //string connectionString = ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString; //Console.WriteLine(connectionString); //ConnectTryFinally(); //ConnectWithUsing(); //AsyncConnection(); ConnInfo(); Console.Read(); } private static void ConnInfo() { string connectionString = @"Data Source=.\SQLEXPRESS01;Initial Catalog=usersdb;Integrated Security=True"; using (SqlConnection connection = new SqlConnection(connectionString)) { connection.Open(); Console.WriteLine("Подключение открыто"); // Вывод информации о подключении Console.WriteLine("Свойства подключения:"); Console.WriteLine("\tСтрока подключения: {0}", connection.ConnectionString); Console.WriteLine("\tБаза данных: {0}", connection.Database); Console.WriteLine("\tСервер: {0}", connection.DataSource); Console.WriteLine("\tВерсия сервера: {0}", connection.ServerVersion); Console.WriteLine("\tСостояние: {0}", connection.State); Console.WriteLine("\tWorkstationld: {0}", connection.WorkstationId); } Console.WriteLine("Подключение закрыто..."); } private static void AsyncConnection() { ConnectWithDB().GetAwaiter(); } private static async Task ConnectWithDB() { string connectionString = @"Data Source=.\SQLEXPRESS;Initial Catalog=usersdb;Integrated Security=True"; using (SqlConnection connection = new SqlConnection(connectionString)) { await connection.OpenAsync(); Console.WriteLine("Подключение открыто"); } Console.WriteLine("Подключение закрыто..."); } private static void ConnectWithUsing() { //string connectionString = @"Data Source=.\SQLEXPRESS01;Initial Catalog=usersdb;Integrated Security=True"; string connectionString = ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString; using (SqlConnection connection = new SqlConnection(connectionString)) { connection.Open(); Console.WriteLine("Подключение открыто"); } Console.WriteLine("Подключение закрыто..."); } private static void ConnectTryFinally() { //string connectionString = @"Data Source=.\SQLEXPRESS01;Initial Catalog=usersdb;Integrated Security=True"; string connectionString = ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString; // Создание подключения SqlConnection connection = new SqlConnection(connectionString); try { // Открываем подключение connection.Open(); Console.WriteLine("Подключение открыто"); } catch (SqlException ex) { Console.WriteLine(ex.Message); } finally { // закрываем подключение connection.Close(); Console.WriteLine("Подключение закрыто..."); } } } } |
Posted in C#
Comments Off on C#. ADO.Net. Connection
C#. Serialization to XML and serialization of collections
Example from Troelsen see methods // XML SaveAsXmlFormat(jbc, “CarData.xml”); SaveListOfCars();
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 |
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; // Gain access to the BinaryFormatter in mscorlib.dll. using System.Runtime.Serialization.Formatters.Binary; // Must reference System.Runtime.Serialization.Formatters.Soap.dll. using System.Runtime.Serialization.Formatters.Soap; // Defined within System.Xml.dll. using System.Xml.Serialization; using System.IO; namespace SimpleSerialize { #region Types to serialize [Serializable] public class Radio { public bool hasTweeters; public bool hasSubWoofers; public double[] stationPresets; [NonSerialized] public string radioID = "XF-552RR6"; } [Serializable] public class Car { public Radio theRadio = new Radio(); public bool isHatchBack; } [Serializable] [XmlRoot(Namespace = "http://www.MyCompany.com")] public class JamesBondCar : Car { [XmlAttribute] public bool canFly; [XmlAttribute] public bool canSubmerge; public JamesBondCar(bool skyWorthy, bool seaWorthy) { canFly = skyWorthy; canSubmerge = seaWorthy; } // The XmlSerializer demands a default constructor! public JamesBondCar() { } } #endregion class Program { // Be sure to import the System.Runtime.Serialization.Formatters.Binary // and System.IO namespaces. static void Main(string[] args) { Console.WriteLine("***** Fun with Object Serialization *****\n"); // Make a JamesBondCar and set state. JamesBondCar jbc = new JamesBondCar(); jbc.canFly = true; jbc.canSubmerge = false; jbc.theRadio.stationPresets = new double[] { 89.3, 105.1, 97.1 }; jbc.theRadio.hasTweeters = true; // Now save the car to a specific file in a binary format. SaveAsBinaryFormat(jbc, "CarData.dat"); LoadFromBinaryFile("CarData.dat"); // Save as SOAP. SaveAsSoapFormat(jbc, "CarData.soap"); // XML SaveAsXmlFormat(jbc, "CarData.xml"); SaveListOfCars(); Console.ReadLine(); } #region Load from binary static void LoadFromBinaryFile(string fileName) { BinaryFormatter binFormat = new BinaryFormatter(); // Read the JamesBondCar from the binary file. using (Stream fStream = File.OpenRead(fileName)) { JamesBondCar carFromDisk = (JamesBondCar)binFormat.Deserialize(fStream); Console.WriteLine("Can this car fly? : {0}", carFromDisk.canFly); } } #endregion #region Save as binary static void SaveAsBinaryFormat(object objGraph, string fileName) { // Save object to a file named CarData.dat in binary. BinaryFormatter binFormat = new BinaryFormatter(); using (Stream fStream = new FileStream(fileName, FileMode.Create, FileAccess.Write, FileShare.None)) { binFormat.Serialize(fStream, objGraph); } Console.WriteLine("=> Saved car in binary format!"); } #endregion #region Save as SOAP // Be sure to import System.Runtime.Serialization.Formatters.Soap // and reference System.Runtime.Serialization.Formatters.Soap.dll. static void SaveAsSoapFormat(object objGraph, string fileName) { // Save object to a file named CarData.soap in SOAP format. SoapFormatter soapFormat = new SoapFormatter(); using (Stream fStream = new FileStream(fileName, FileMode.Create, FileAccess.Write, FileShare.None)) { soapFormat.Serialize(fStream, objGraph); } Console.WriteLine("=> Saved car in SOAP format!"); } #endregion #region Save as XML static void SaveAsXmlFormat(object objGraph, string fileName) { // Save object to a file named CarData.xml in XML format. XmlSerializer xmlFormat = new XmlSerializer(typeof(JamesBondCar)); using (Stream fStream = new FileStream(fileName, FileMode.Create, FileAccess.Write, FileShare.None)) { xmlFormat.Serialize(fStream, objGraph); } Console.WriteLine("=> Saved car in XML format!"); } #endregion #region Save LIST of objects static void SaveListOfCars() { // Now persist a List<T> of JamesBondCars. List<JamesBondCar> myCars = new List<JamesBondCar>(); myCars.Add(new JamesBondCar(true, true)); myCars.Add(new JamesBondCar(true, false)); myCars.Add(new JamesBondCar(false, true)); myCars.Add(new JamesBondCar(false, false)); using (Stream fStream = new FileStream("CarCollection.xml", FileMode.Create, FileAccess.Write, FileShare.None)) { XmlSerializer xmlFormat = new XmlSerializer(typeof(List<JamesBondCar>)); xmlFormat.Serialize(fStream, myCars); } Console.WriteLine("=> Saved list of cars!"); } static void SaveListOfCarsAsBinary() { // Save ArrayList object (myCars) as binary. List<JamesBondCar> myCars = new List<JamesBondCar>(); BinaryFormatter binFormat = new BinaryFormatter(); using (Stream fStream = new FileStream("AllMyCars.dat", FileMode.Create, FileAccess.Write, FileShare.None)) { binFormat.Serialize(fStream, myCars); } Console.WriteLine("=> Saved list of cars in binary!"); } #endregion } } |
Posted in C#
Comments Off on C#. Serialization to XML and serialization of collections
C#. SystemIO. SoapFormatter
MSDN
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 |
using System; using System.IO; using System.Collections; using System.Runtime.Serialization; // Note: When building this code, you must reference the // System.Runtime.Serialization.Formatters.Soap.dll assembly. using System.Runtime.Serialization.Formatters.Soap; class App { [STAThread] static void Main() { Serialize(); Deserialize(); } static void Serialize() { // Create a hashtable of values that will eventually be serialized. Hashtable addresses = new Hashtable(); addresses.Add("Jeff", "123 Main Street, Redmond, WA 98052"); addresses.Add("Fred", "987 Pine Road, Phila., PA 19116"); addresses.Add("Mary", "PO Box 112233, Palo Alto, CA 94301"); // To serialize the hashtable (and its key/value pairs), // you must first open a stream for writing. // Use a file stream here. FileStream fs = new FileStream("DataFile.soap", FileMode.Create); // Construct a SoapFormatter and use it // to serialize the data to the stream. SoapFormatter formatter = new SoapFormatter(); try { formatter.Serialize(fs, addresses); } catch (SerializationException e) { Console.WriteLine("Failed to serialize. Reason: " + e.Message); throw; } finally { fs.Close(); } } static void Deserialize() { // Declare the hashtable reference. Hashtable addresses = null; // Open the file containing the data that you want to deserialize. FileStream fs = new FileStream("DataFile.soap", FileMode.Open); try { SoapFormatter formatter = new SoapFormatter(); // Deserialize the hashtable from the file and // assign the reference to the local variable. addresses = (Hashtable) formatter.Deserialize(fs); } catch (SerializationException e) { Console.WriteLine("Failed to deserialize. Reason: " + e.Message); throw; } finally { fs.Close(); } // To prove that the table deserialized correctly, // display the key/value pairs to the console. foreach (DictionaryEntry de in addresses) { Console.WriteLine("{0} lives at {1}.", de.Key, de.Value); } } } |
Posted in C#
Comments Off on C#. SystemIO. SoapFormatter
C#. SystemIO. BinaryFormatter
MSDN
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 |
using System; using System.IO; using System.Collections; using System.Runtime.Serialization.Formatters.Binary; using System.Runtime.Serialization; public class App { [STAThread] static void Main() { Serialize(); Deserialize(); } static void Serialize() { // Create a hashtable of values that will eventually be serialized. Hashtable addresses = new Hashtable(); addresses.Add("Jeff", "123 Main Street, Redmond, WA 98052"); addresses.Add("Fred", "987 Pine Road, Phila., PA 19116"); addresses.Add("Mary", "PO Box 112233, Palo Alto, CA 94301"); // To serialize the hashtable and its key/value pairs, // you must first open a stream for writing. // In this case, use a file stream. FileStream fs = new FileStream("DataFile.dat", FileMode.Create); // Construct a BinaryFormatter and use it to serialize the data to the stream. BinaryFormatter formatter = new BinaryFormatter(); try { formatter.Serialize(fs, addresses); } catch (SerializationException e) { Console.WriteLine("Failed to serialize. Reason: " + e.Message); throw; } finally { fs.Close(); } } static void Deserialize() { // Declare the hashtable reference. Hashtable addresses = null; // Open the file containing the data that you want to deserialize. FileStream fs = new FileStream("DataFile.dat", FileMode.Open); try { BinaryFormatter formatter = new BinaryFormatter(); // Deserialize the hashtable from the file and // assign the reference to the local variable. addresses = (Hashtable) formatter.Deserialize(fs); } catch (SerializationException e) { Console.WriteLine("Failed to deserialize. Reason: " + e.Message); throw; } finally { fs.Close(); } // To prove that the table deserialized correctly, // display the key/value pairs. foreach (DictionaryEntry de in addresses) { Console.WriteLine("{0} lives at {1}.", de.Key, de.Value); } } } |
Posted in C#
Comments Off on C#. SystemIO. BinaryFormatter