Connect to MS SQL database

*** SOLVED ***

The request below has been solved by simply replacing the database name with the IP Address. For example:

DatabaseSever\DatabaseName:\DatabaseInstance needs changing to
IPAddress\DatabaseName\DatabaseInstance

Hi all,

I’ve seen other similar questions and feel like I have everything setup correctly, save one config option.

Using C# code from my VisualStudio project which connects to my database correctly, I am getting the following error when executing the request in Unity:

System.Data.SqlClient.SqlException: SQL Server does not exist or access denied.

I have ensured that System.Data.dll resides in the correct project folder and have also enabled TCP/IP on the database.

Can anybody help with me the last part to this puzzle?

The code I am using is:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Data;
using System.Data.SqlClient;
using System.Text;
using UnityEngine.UI;
using UnityEngine;


namespace DatabaseConnectionTest
{
    public class SQLFunctions : MonoBehaviour
    {
        public InputField inputDBInstance;
        public InputField username;
        public InputField password;
        public Text connectionStatus;

        public static bool RemoteDBConnection = false;

        void Start()
        {

            inputDBInstance.text = "";
            connectionStatus.text = "No";
        }

        static SqlDataAdapter TableDataFetcher;
        static DataTable SQLDataTable;
        public static SqlConnection AppConnection = new SqlConnection();
        static SqlCommand SQLCommand = new SqlCommand();
        static UnityEngine.Random RandomNumber = new UnityEngine.Random();
        private static readonly UnityEngine.Random RandomBase = new UnityEngine.Random();

        public static void FConnectToDatabase(string DBServer, string SQLServerInstance, string Database, string UserName, string Password)
        {
            AppConnection = new SqlConnection(string.Format(@"Data Source={0}\{1}; Initial Catalog={2}; User id={3}; Password={4};", DBServer + (RemoteDBConnection == true ? ".ksdl.local" : ""),"Initial Catalogue=" + SQLServerInstance, Database, UserName, Password));

            if (AppConnection == null)
            {
                AppConnection = new SqlConnection() { ConnectionString = "INVALID" };
            }
        }

        public static void FOpenConnection(SqlConnection ConnectionString)
        {
            try
            {
                if (ConnectionString.ConnectionString == "INVALID")
                {
                    throw new Exception();
                }

                if (ConnectionString.State == ConnectionState.Closed)
                {
                    ConnectionString.Open();
                }
            }
            catch (Exception ex)
            {
                FException(ex);
            }
        }

        public static void FCloseConnection(SqlConnection ConnectionString)
        {
            try
            {
                if (ConnectionString.State == ConnectionState.Open)
                {
                    ConnectionString.Close();
                }
            }
            catch (Exception ex)
            {
                FException(ex);
            }
        }

        public static void FGetStockTypes(ref DataTable Table, SqlConnection Connection)
        {
            try
            {
                TableDataFetcher = new SqlDataAdapter("SELECT SHORT_DESC FROM stock_type", Connection);
                TableDataFetcher.Fill(Table);
            }
            catch (Exception ex)
            {
                FException(ex);
            }
        }
        public static void FException(string ExceptionMessage, string ExceptionTitle = "ERROR!")

        {
            //MessageBox.Show(ExceptionMessage, ExceptionTitle, Buttons);
            Debug.Log("Error");
        
        }

        public static void FException(Exception ex, string ExceptionTitle = "ERROR!")
        {
            if (ex.InnerException != null && ex.InnerException.InnerException != null)
            {
                Debug.Log(ex);
            }
            else if (ex.InnerException != null && ex.InnerException.Message != null)
            {
                Debug.Log(ex);
            }
            else
            {
                Debug.Log(ex);
            }
        }

        public void OnDatabaseConnectButton_Click()
        {
            string[] ConnectionStringElements = inputDBInstance.text.Split(new string[] { "\\", ":" }, StringSplitOptions.RemoveEmptyEntries);

            if (ConnectionStringElements.Length != 3)
            {
                Debug.LogError("Invalid Connection string entered!");
            }
            else
            {
                FConnectToDatabase(ConnectionStringElements[0], ConnectionStringElements[1], ConnectionStringElements[2], username.text, password.text);

                FOpenConnection(SQLFunctions.AppConnection);

                if (AppConnection.State == ConnectionState.Open)
                {
                    connectionStatus.text = "Connection Successful";
                    FCloseConnection(AppConnection);
                }
            }
        }


    }
}

Use code tags!

People will be more willing to help.

Thank you for the suggestion @TaleOf4Gamers_1 . I’m such a noob

this is a common connection issue in SQL. The issue is your connection string. Here is a suggested example:

connetionString = “Data Source=ServerName;Initial Catalog=DatabaseName;User ID=UserName;Password=Password”;

and here is a link to documents on how to connect

I recommend you just google how to connect to Microsoft SQL using c#. Most results will be for .Net framework which is fine it should be the same syntax in Mono I assume. If you have not viewed the Microsoft MSDN forums, I highly recommend you familiarize your self with it as well. Stack Overflow is another great place for c# related issues and SQL stuff. To answer your question though your error is in your connection string. Check our Server Name, Database Name, User Name and Password. Also make sure you have given asses to that database for that user. I honestly make a generic user that has read and write access for my SQL databases and limit their access for apps. So each app I create has a limited user I make that can execute stored procs etc but only use is for that app and that database specially.

Side note, I recommend you consider switching to an API approach to call your SQL commands/procs. Having a DLL with connection info can easly be exposed and your data can be compromised. Direct calls are no longer secure. I hope that all makes sense. Please feel free to request additional info about SQL if you need help. I’m a .Net dev by trade but newb to Unity lol

2 Likes

I would like to thank mholmes for providing a direct answer to the issue without insisting the user switch to an API approach. I have spent many hours searching unity forums trying to learn how to connect unity to a database only to be admonished for attempting to connect to a database directly. Unity is being used in many use cases that need direct database access to facilitate dynamic sql communication with the database. Data visualization solutions and process simulation solutions implemented using unity are among those use cases. For these use cases storing the password is of minimal risk due to the use of read only database accounts as recommended by mholmes. My frustration with the unity community’s inability to see beyond the API approach of database access. Client server software architecture is still an acceptable strategy versus multi tier software architecture. Thank you mholmes for assisting us new to unity.

2 Likes