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
|
using System;
using System.Data;
using System.Data.SqlClient;
namespace ExempleInsertSelect
{
class Program
{
static void Main(string[] args)
{
Random rnd = new Random();
while (true)
{
using (SqlConnection cnx = new SqlConnection(@"Server=.\SQL2016;Database=SandBox;Trusted_Connection=True;"))
{
cnx.Open();
SqlCommand cmd = cnx.CreateCommand();
cmd.CommandText = "insert into dbo.aleatoire (num) output inserted.id, inserted.num values (@num)";
SqlParameter pNum = cmd.CreateParameter();
pNum.ParameterName = "num";
pNum.SqlDbType = SqlDbType.Int;
pNum.Value = rnd.Next(1000);
cmd.Parameters.Add(pNum);
cmd.Prepare();
SqlDataReader dr = cmd.ExecuteReader(CommandBehavior.SequentialAccess | CommandBehavior.SingleResult | CommandBehavior.SingleRow);
if (dr.Read())
{
Console.WriteLine("Nouvelle ligne insérée :");
Console.WriteLine("ID\tNUM");
Console.WriteLine("{0}\t{1}", dr.GetInt32(0), dr.GetInt32(1));
}
else
{
Console.WriteLine("Pas normal, le INSERT n'a créé aucune ligne, il aurait du planter !");
}
dr.Close();
cmd.CommandText = "select count(*), avg(num), min(num), max(num) from dbo.aleatoire";
cmd.Parameters.Clear();
cmd.Prepare();
dr = cmd.ExecuteReader(CommandBehavior.SequentialAccess | CommandBehavior.SingleResult | CommandBehavior.SingleRow);
Console.WriteLine("Informations sur les lignes présentes dans la base :");
Console.WriteLine("NOMBRE\tMOYENNE\tMINIMUM\tMAXIMUM");
while (dr.Read())
{
Console.WriteLine("{0}\t{1}\t{2}\t{3}", dr.GetInt32(0), dr.GetInt32(1), dr.GetInt32(2), dr.GetInt32(3));
}
dr.Close();
cnx.Close();
}
Console.WriteLine("Appuyer sur Echap pour terminer, ou sur une autre touche pour continuer");
if (Console.ReadKey(true).Key == ConsoleKey.Escape)
{
break;
}
}
}
}
} |
Partager