Advertisement
Guest User

Untitled

a guest
Nov 22nd, 2017
87
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.23 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Data.Common;
  4. using System.Linq;
  5. using System.Text;
  6. using System.Threading.Tasks;
  7.  
  8. namespace fun12Test
  9. {
  10.     static class Database
  11.     {
  12.         private const string provider = "System.Data.SqlClient";
  13.         private const string connectionString = "Data Source=DESKTOP-UF0PRTR;Initial Catalog=funTest;Integrated Security=True";
  14.  
  15.         private static DbProviderFactory factory = DbProviderFactories.GetFactory(provider);
  16.         private static DbConnection connection = factory.CreateConnection();
  17.  
  18.         public static bool Connect()
  19.         {
  20.             // DbProviderFactories generates an
  21.             // instance of a DbProviderFactory
  22.            
  23.  
  24.             // The DBConnection represents the DB connection
  25.                 // Check if a connection was made
  26.                 if (connection == null)
  27.                 {
  28.                     Console.WriteLine("Connection Error");
  29.                     Console.ReadLine();
  30.                     return false;
  31.                 }
  32.  
  33.                 // The DB data needed to open the correct DB
  34.                 connection.ConnectionString = connectionString;
  35.  
  36.                 // Open the DB connection
  37.                 connection.Open();
  38.  
  39.                 return true;
  40.         }
  41.  
  42.         public static DbDataReader sql(string sql)
  43.         {
  44.            
  45.                 // Allows you to pass queries to the DB
  46.                 DbCommand command = factory.CreateCommand();
  47.  
  48.                 if (command == null)
  49.                 {
  50.                     Console.WriteLine("Command Error");
  51.                     if (!Connect())
  52.                     {
  53.                         throw new Exception("Something went terrebly wrong");
  54.                     }
  55.                 }
  56.  
  57.                 // Set the DB connection for commands
  58.                 command.Connection = connection;
  59.  
  60.                 // The query you want to issue
  61.                 command.CommandText = sql;
  62.  
  63.  
  64.             // DbDataReader reads the row results
  65.             // from the query
  66.             DbDataReader dataReader = command.ExecuteReader();
  67.             // Advance to the next results
  68.             return dataReader;
  69.            
  70.         }
  71.     }
  72. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement