SqlServerDB_dotNET 2.1.0

dotnet add package SqlServerDB_dotNET --version 2.1.0
                    
NuGet\Install-Package SqlServerDB_dotNET -Version 2.1.0
                    
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="SqlServerDB_dotNET" Version="2.1.0" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="SqlServerDB_dotNET" Version="2.1.0" />
                    
Directory.Packages.props
<PackageReference Include="SqlServerDB_dotNET" />
                    
Project file
For projects that support Central Package Management (CPM), copy this XML node into the solution Directory.Packages.props file to version the package.
paket add SqlServerDB_dotNET --version 2.1.0
                    
#r "nuget: SqlServerDB_dotNET, 2.1.0"
                    
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
#:package SqlServerDB_dotNET@2.1.0
                    
#:package directive can be used in C# file-based apps starting in .NET 10 preview 4. Copy this into a .cs file before any lines of code to reference the package.
#addin nuget:?package=SqlServerDB_dotNET&version=2.1.0
                    
Install as a Cake Addin
#tool nuget:?package=SqlServerDB_dotNET&version=2.1.0
                    
Install as a Cake Tool

SqlServerDB — Documentazione NuGet

Una piccola libreria per semplificare la connessione a Microsoft SQL Server e l’esecuzione di query con C#/.NET.

Installazione

CLI

dotnet add package SqlServerDB

Package Manager

Install-Package SqlServerDB

Requisiti: .NET (Framework o .NET 6+), accesso a un’istanza SQL Server raggiungibile.


Avvio rapido (Quick Start)

using System;
using System.Data;
using SqlServerDB;

class Program
{
    static void Main()
    {
        string server   = @"INSTANCE\\SQLEXPRESS";
        string database = "DEMODB";
        string username = "sa";
        string password = "";

        string connectionString =
            $"Data Source={server};Initial Catalog={database};Trusted_Connection=True;User ID={username};Password={password}";

        DBConnection db_conn = new DBConnection(connectionString);

        Console.WriteLine($"IsConnected: {db_conn.IsConnected()}");
        if (db_conn == null || !db_conn.IsConnected())
        {
            Console.WriteLine("Connessione non valida.");
            return;
        }

        Console.WriteLine($"GetVersion: {db_conn.GetVersion()}");
        Console.WriteLine($"ConnectionString: {connectionString}");
        Console.WriteLine($"GetConnectionTimeout: {db_conn.GetConnectionTimeout()}");
        Console.WriteLine($"Host: {db_conn.Server}");
        Console.WriteLine($"Database: {db_conn.Database}");
        Console.WriteLine($"UserID: {db_conn.UserID}");
        Console.WriteLine($"Password: {db_conn.Password}");

        // Lettura dati
        string sql = "SELECT ID, Message FROM Logs ORDER BY IDLic;";
        DataTable dtLogs = db_conn.SelectTable(sql);
        if (dtLogs == null || dtLogs.Rows.Count == 0) return;

        foreach (DataRow dr in dtLogs.Rows)
        {
            Console.WriteLine("Message: " + dr["Message"].ToString().Trim());
        }

        // Scrittura dati con 'using' (dispose automatico)
        using (DBConnection db2 = new DBConnection(connectionString))
        {
            string sNominativo = "Micky";
            string insertSql = "INSERT INTO TabLav (Nominativo) VALUES('" + sNominativo + "');";

            if (!db2.sql_query(insertSql))
            {
                Console.WriteLine("Error during insert: " + db2.sql_error()[0]);
                Console.WriteLine(insertSql);
            }

            int insertedID = db2.GetLastInsertedRowID();
            Console.WriteLine("GetLastInsertedRowID: " + insertedID);

            int recordsAffected = db2.GetNumRecordsAffected();
            Console.WriteLine("GetNumRecordsAffected: " + recordsAffected);
        }
    }
}

Connection string — esempi

  • Windows Authentication (Trusted Connection)

    Data Source=SERVER\\INSTANCE;Initial Catalog=DEMODB;Trusted_Connection=True;
    
  • SQL Authentication

    Data Source=SERVER\\INSTANCE;Initial Catalog=DEMODB;User ID=sa;Password=yourPwd;
    
  • Timeout personalizzato

    Data Source=SERVER\\INSTANCE;Initial Catalog=DEMODB;User ID=sa;Password=yourPwd;Connection Timeout=30;
    

Evita di loggare password/connection string complete in produzione.


API (sintesi)

Costruttore

  • DBConnection(string connectionString)

Proprietà

  • string Server — Host/istanza
  • string Database — Database selezionato
  • string UserID
  • string Password

Metodi

  • bool IsConnected() — stato connessione
  • string GetVersion() — versione server SQL
  • int GetConnectionTimeout() — timeout (s)
  • DataTable SelectTable(string sql) — SELECT → DataTable (o null)
  • bool sql_query(string sql) — INSERT/UPDATE/DELETE/DDL
  • string[] sql_error() — ultimi dettagli d’errore
  • int GetLastInsertedRowID() — ID dell’ultima riga inserita
  • int GetNumRecordsAffected() — record interessati dall’ultima non-query

La classe implementa IDisposable. Usa sempre using per il rilascio delle risorse.


Esempi aggiuntivi

Lettura semplice

DataTable dt = db_conn.SelectTable("SELECT TOP 100 * FROM Logs;");
if (dt != null)
{
    foreach (DataRow r in dt.Rows)
        Console.WriteLine($"{r["ID"]}: {r["Message"]}");
}

Inserimento con controllo errori

string name = "Mario Rossi";
string insert = $"INSERT INTO TabClienti (Nome) VALUES('{name}');";

if (!db_conn.sql_query(insert))
{
    var errors = db_conn.sql_error();
    Console.WriteLine("Errore SQL: " + (errors?.Length > 0 ? errors[0] : "sconosciuto"));
}
else
{
    Console.WriteLine($"Nuovo ID: {db_conn.GetLastInsertedRowID()}");
    Console.WriteLine($"Record interessati: {db_conn.GetNumRecordsAffected()}");
}

Sicurezza: gli esempi concatenano stringhe per semplicità. In produzione usa query parametriche o stored procedure per prevenire SQL injection.


Troubleshooting

  • IsConnected() è false
    Verifica Data Source, Initial Catalog, credenziali, firewall/porte. Aumenta Connection Timeout temporaneamente.

  • SelectTable ritorna null
    Query non valida o eccezione: controlla sql_error(). Verifica permessi.

  • GetLastInsertedRowID() è 0
    Assicurati che la tabella abbia una colonna IDENTITY o meccanismo equivalente e che la chiamata avvenga sulla stessa istanza dopo l’INSERT.


Licenza & Changelog

Consulta la pagina NuGet del pacchetto per note di rilascio e licenza.

Product Compatible and additional computed target framework versions.
.NET Framework net40 is compatible.  net403 was computed.  net45 was computed.  net451 was computed.  net452 was computed.  net46 was computed.  net461 was computed.  net462 was computed.  net463 was computed.  net47 was computed.  net471 was computed.  net472 was computed.  net48 was computed.  net481 was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

This package has no dependencies.

NuGet packages

This package is not used by any NuGet packages.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
2.1.0 77 12/13/2025
2.0.4 916 3/6/2023
2.0.3 780 3/6/2023
2.0.2 1,049 2/9/2021
2.0.1 967 2/9/2021
2.0.0 962 2/7/2021
1.3.4 1,074 12/3/2020
1.3.3 987 11/2/2020
1.3.2 1,103 10/23/2020
1.3.1 1,118 10/13/2020
1.3.0 1,063 10/12/2020
1.2.2 1,132 10/1/2020
1.2.1 1,076 9/27/2020
1.2.0 1,094 9/20/2020
1.1.3 1,065 8/18/2020
1.1.2 1,063 8/17/2020
1.1.1 1,150 8/12/2020
1.1.0 1,069 8/12/2020
1.0.0 1,356 12/8/2018

Extensions on the SqlServerDB .NetFramework.