16 August 2025

Python - Execute a query with pyodbc

To work with a database via ODBC, first install the PyOdbc package and import it. The following simple query shows how to execute a select query and return data:
import pyodbc

def get_user(username) -> int:   
    with pyodbc.connect("Server=(LocalDB)\Test; Integrated Security=true; Driver={ODBC Driver 17 for SQL Server}") as conn:
        with conn.execute("SELECT id FROM Users WHERE username=?", username) as cursor:
            rows = cursor.fetchall()
    
    if len(rows) <= 0:
        return
    
    return rows[0].id

print(f"user ID: {get_user("EGS")}")

24 June 2025

.NET - Read/write a binary file line by line

To read a text file, you can use a StreamReader, but to read a binary file, you need a BinaryReader.This is how you use it:

if (File.Exists(FILENAME))
{
    using (var stream = new FileStream(FILENAME, FileMode.Open))
    using (var reader = new BinaryReader(stream))
    {
        if (stream.Length <= 0) return; //The file is empty.
        int i = reader.ReadInt32();
        string s = reader.ReadString();
    }
}

Writing is similar:

using (var stream = new FileStream(SaveFilePath, FileMode.Create))
using (var writer = new BinaryWriter(stream))
{
    writer.Write(305);
    writer.Write("EGS");
}

The file will be automatically created if it doesn't exist yet.