Advertisement
Guest User

Untitled

a guest
May 28th, 2017
62
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.30 KB | None | 0 0
  1. using UnityEngine;
  2. using System;
  3. using System.Collections;
  4. using System.Data;
  5. using System.Data.Sql;
  6. using System.Data.SqlClient;
  7.  
  8. public class SQLDatabase : MonoBehaviour {
  9.     // Global variables
  10.     private static IDbConnection dbConnection;
  11.     public static float dollars;
  12.     public static float Lodging;
  13.     public static float Vehicles;
  14.  
  15.     // Initialisation
  16.     public void OnEnable() {
  17.         Debug.Log("SQLDatabase.Awake()");
  18.         openSqlConnection();        
  19.         //displayBank();
  20.     }
  21.    
  22.     // Connect to database
  23.     private static void openSqlConnection() {
  24.         string connectionString = "Data source = localhost\\DEVILSZONE\\SQLEXPRESS;" +
  25.             "Database=safariville;" +
  26.             "Integrated security=True;"+
  27.             "Pooling=false;";
  28.         try {
  29.             dbConnection = new SqlConnection(connectionString);
  30.             dbConnection.Open();
  31.             Debug.Log("DATABASE connected");
  32.         }  catch(Exception ex) {
  33.             Debug.LogWarning("Could not connect to DB, got: " + ex.ToString());
  34.             dbConnection = null;
  35.         }
  36.     }
  37.    
  38.     // MySQL Query
  39.     public static void displayBank() {
  40.         try {
  41.             IDbCommand dbCommand = dbConnection.CreateCommand();
  42.             dbCommand.CommandText = "SELECT * FROM safariville.dbo.bank WHERE SCash = 3000.00";
  43.             Debug.Log("SELECT executed");
  44.             IDataReader reader = dbCommand.ExecuteReader();
  45.             // Executing or Getting the data from the databse
  46.             while (reader.Read())
  47.             {
  48.                 dollars = reader.GetFloat(0);
  49.                 Lodging = reader.GetFloat(3);
  50.                 Debug.Log("bank: " + Lodging);
  51.                 Vehicles = reader.GetFloat(4);
  52.                 Debug.Log("bank: " + Vehicles);
  53.             }
  54.             reader.Close();
  55.             reader = null;
  56.             dbCommand.Dispose();
  57.             dbCommand = null;
  58.         } catch (Exception ex) {
  59.             Debug.Log(ex);
  60.         }
  61.     }
  62.  
  63.     // Disconnect from database
  64.     private static void closeSqlConnection() {
  65.         if(dbConnection != null) {
  66.             dbConnection.Close();
  67.             dbConnection = null;
  68.         }
  69.     }
  70.  
  71.     // On quit
  72.     public void OnApplicationQuit() {
  73.         closeSqlConnection();
  74.     }
  75. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement