Starting my MMO with SQL SERVER! in Javascript

Hi everyone!, I was looking for a tutorial, who can make me learn SQL on UNITY, so, everyone just scary me!
Thanks for Tempest, and Xandeck, but i want something more, and more simple, so, i will share with you guys what i’ve learn, I’m from Brasil, so, my english is from video games! :smile:,

Here we are going to learn:

  • Connecting Unity to a Database, with login and Password
  • Making a Search using Select.
  • Have results from the database to use.
  • Use what we have got.

Starting:

First, you are going to have a database running on a server, (i don’t intend to explain this, cause i don’t know, i’ve got a server from my company to test, later i’ll explain, when i learn someday, maybe), but, with a server running, create a new Unity Project, name it whatever you like, and don’t import anything, because it’s faster this way :smile:, and then, create a single Javascript file, rename it to whatever you like, and let’s start the cool stuff!

The Headers:

Type it there!

import System;
import System.Data;
import System.Data.SqlClient;

Yes! We are using C# libs in Javascript!, we are sooo bad :sunglasses:

Observations:

And now, create a Start function to test the code.

function Start () {
[INDENT]//and don't belive i've teaching this! sorry for making you feel like a noob![/INDENT]
}

The Harder part:

And now, ladies and gentlemans, the connection comand!

lets create the main class object of the connection:

var dbcon : IDbConnection;

you can name dbcon to DATABASE, to be more intuitive.
and lets do the connection:

var connectionString : String =
	"Server=xxx.xxx.xxx.xxx;" + // put the ip here!
	"Database=INSERT DATABASE NAME HERE;" +
	"User ID=INSERT LOGIN HERE;" +
	"Password=INSERT PASSWORD HERE;";
dbcon = new SqlConnection(connectionString);
dbcon.Open();

We created a var to store the “url” to the bank, and Instantiate the class for connections.
Remenber: we are using SQL Server, (in my case, SQL Server 2008 R2), but i’m sure it can work with SQlite, Oracle, or something else, all you need to do for it to work, its learn,

You can: search for a code that have connection to the base you want, and just look for the Connection String.

And now, we are going to make a SQL command, the classic, the one, the awesome, SELECT!

//create the class EXECUTIONER, that execute SQL commands
var dbcmd : IDbCommand = dbcon .CreateCommand();
//string var, to save the command we want to use
var cmdSql : String = SELECT [COLOR="blue"]idUsuario[/COLOR], [COLOR="blue"]nmUsuario[/COLOR], [COLOR="blue"]dsLogin[/COLOR], [COLOR="blue"]dsSenha [/COLOR]FROM [COLOR="#ff8c00"]FestaJunina[/COLOR].[COLOR="red"]tbUsuario[/COLOR];
//we add the command, as string, to the executor, to shot it!
dbcmd.CommandText = cmdSql;
//and then, we create a table, like a normal db table, to use it on unity, and we use the function that "plays" the command
var reader : IDataReader = dbcmd.ExecuteReader();

Subtitle of colors:
Blue: Columns Names.
Orange: Main Database name.
Red: Table name.

this all that we made till here, did:

  • Conected to the database
  • Send a command
  • Execute a command
  • Returned results

Now, lets read what we got from the database! :smile:

while(reader .Read()) {
		var id : String = reader ["[COLOR="#2e8b57"]idUsuario[/COLOR]"].ToString();
		var nome : String = reader ["[COLOR="#2e8b57"]nmUsuario[/COLOR]"].ToString();
		var login : String = reader ["[COLOR="#2e8b57"]dsLogin[/COLOR]"].ToString();
		var senha : String = reader ["[COLOR="#2e8b57"]dsSenha[/COLOR]"].ToString();
		print ("ID: " + id + "NAME: " + nome + "LOGIN: " + login + "PASSWORD: " + senha);
	}

This 'll make the following thing:
For every while loop, the table we created to store the table that is the result of our query on the database, the reader jumps to the next line.

Did you get it? No?
hahahahahaha, man! i have to go to a english school! Humpf :frowning:

Ok, "reader " is the name of my table, that holds the data i’ve got from my search. ok?
The reader could have n lines, and have 4 columns, and they are: id, name, login, password.
we need to go on every line, to read it, column by column. (it’s column right? or Colunm? or, whatever…)

Green: Name that i’ve used to created the table.

and, after that, use:

reader .Close();
reader = null;
dbcon.Close();
dbcon = null;

I now you got what this code means.

This is it!

In my unity it have returned:

ID: 1 NAME: Daniel LOGIN: daniel@XxXxXx.com.br PASSWORD: 123456
UnityEngine.MonoBehaviour:print(Object)
ConectaSQLSERVER:Start() (at Assets/ConectaSQLSERVER.js:23)

Hope you got it!
Thanks everyone, any questions, put it in here.
I’ll show later how to create a database, because, i have to get back to work :o my boss its close!

And God bless you all!
because He gives me wisdom for that.

ive been working on something similar recently and ive heard its not safe for your database to have it connect directly through unity. is this true?

i think that a web page can be hacked, and so a software, but a software is so more dificult, because its compiled!, and you can program something inside a unity client, and a unity dedicated server, so that no one will ever know where the database is, and what is the password,so, i think, if no one else have a argument, this kind of connection, can be suficient safe. =]

Unpack dll in unity standalone build or even webplayer build no problem at all, since Reflector and netobf exists.
Use database as game server is not very clever Idea because big lack of security. :shock:

If you plane to make SQL requests from client you need add users directly in to you database with very restricted user role for they. All game logics and checks needs to be placed in to StoredProcedures, Functions, extendet StoredProcedures and etc. All DB operations needs to be processed throug this StoredProcedures/Functions, so data in tables will be on some level of safe. Game performance will be limited by DB performance, which will be not much cause game logics counting is not DB specialised operations. :wink:

You should read through this thread. As Kembl mentioned, Unity games are not compiled. Extracting the source code for a Unity game is as complicated as clicking one button.

http://forum.unity3d.com/threads/17117-Hack-resistance

I believe he’s talking about using a Unity dedicated server for his MMO, connecting it to a database on his network. Not stored procedures through ODBC from the client. That would be a lol-fest.

but to access the database you have to put your database name server name and password right? so those could easily be extracted.

Inspite of all the hacking protection issue, thx for sharing your knowlegde Mr. Bruster, its an awesome tutorial and it worked like a charm!

Way to go friend!

=)

I don’t see a problem with using SQL. The login is handled by the servers anyway and that won’t end on the end users machine, so security constraints wouldn’t exist.

The larger problem is that unity is very unsuitable as backend solution for the MMO
You should definitely not use it as its not performance and you can’t optimize it there. Also unity is not able to use multithreading so you have to split stuff into different servers just for the sake of targeting different cpu cores by setting their cpu affinity on the process.

Using unity networking especially is a big no no as you can’t have dozens of servers running to have a few thousand players especially if using other, more suited solutions would get you 10-40 times as many players at the same cost and it does not offer server - server connections so you have to use system.net and unity networking on the backend to get server - server communication and alike

Unity networking etc are targeted at situations where you players host games or you put up dedicated servers and alike with 4 - 128+ players (128+ only if the networking is as light and non action packed as an MMO though and if you opted it)

thanks dreamora! i not so good with unity, as some legends as Quietus, and, i see so many dificults with sql and other stuff, and i’m fisrt worring about making it work, than making it secure!, and i’m acomplishied (sorry for that, i’m from brazil) this! and i’m so excited! and i want to share it with everyone!, but thanks you!

We lower levels love you Bruster! Thx for all your sharings!

=)

I need to develop a webplayer app and I need to access a database to read the position of the objects, is that possible?

tks,

dani

yes it is

I’ve got to work a webplayer with a simple Register/Login app,
using .asp page to connect to the database, its simple, i’m making a tutorial, soon i’ll send to you!

Just a warning using SQL Server. It uses page locking, and if you use transactions, you can block SELECT queries using the same page. This could be a nightmare accross a WAN where pings are rather large since one SELECT or UPDATE requires miltiple round trips.

To prove this, open two SQL Navigator windows, in one, do a begin trans, and update, no commit or rollback yet. In the second one, SELECT from the same table, you will notice the second SELECT hangs, in the first Navigator window, do a commit or rollback, and in an instant you will see the second SELECT executes. The workaround is to do a SELECT with NOLOCK, but then you will get dirty uncommitted data back.

Design wise its better to send a message to a server to handle updates by sending messages. I dont want people to have a password of my database kept on a client. No matter how little security you give the client account. But again, nothing is unhackable.

What is the correct route of “System.data.dll”? It has many different copies.
I can connect to the SQL Server database inside Unity3.0, but cannot connect after building into a .exe file.
I was told that I’m using a wrong System.data.dll. Anyone can help me?

I wouldn’t directly connect to a database from a Web player or even standalone either - but I guess the examples are still useful for Unity based game servers (which are hosted in the same private network as the database). One thing I’d recommend is putting the database communication to a separate thread (this can get very tricky, especially in Unity - so be careful and understand what you’re doing). That way, stalled database calls can’t freeze the game loop.

Also, make sure to always close your connections. The most elegant way of doing this is using the “using” statement on any variables that need to be closed (see also: using Statement (C# Reference)). Not sure is something equivalent exists in UnityScript; if not, using try { …*} finally { … } also works quite well (and if that doesn’t exist in UnityScript - do not use UnityScript :wink: ).

I tested this with mySQL server on local my MAC… then its error…

here error log:

SocketException: Connection refused
System.Net.Sockets.Socket.Connect (System.Net.EndPoint remoteEP, Boolean requireSocketPolicy)
System.Net.Sockets.Socket+Worker.Connect ()
Rethrow as TdsInternalException: Server does not exist or connection refused.
Mono.Data.Tds.Protocol.TdsComm..ctor (System.String dataSource, Int32 port, Int32 packetSize, Int32 timeout, TdsVersion tdsVersion)
Mono.Data.Tds.Protocol.Tds..ctor (System.String dataSource, Int32 port, Int32 packetSize, Int32 timeout, TdsVersion tdsVersion)
Mono.Data.Tds.Protocol.Tds70..ctor (System.String server, Int32 port, Int32 packetSize, Int32 timeout, TdsVersion version)
Mono.Data.Tds.Protocol.Tds80..ctor (System.String server, Int32 port, Int32 packetSize, Int32 timeout)
Mono.Data.Tds.Protocol.TdsConnectionPoolManager.CreateConnection (Mono.Data.Tds.Protocol.TdsConnectionInfo info)
Mono.Data.Tds.Protocol.TdsConnectionPool.GetConnection ()
System.Data.SqlClient.SqlConnection.Open ()

can anyone direct me to a MySQL tutorial to set it up and start building a database? I have no idea what I’m doing with the database. I have stuff installed but can’t really get it to do anything…

http://www.google.be/#hl=nl&source=hp&biw=1376&bih=1012&q=mysql+howto&aq=f&aqi=g6&aql=&oq=&fp=fdb7ce9e46ebd481

Like you are from Brasil, I am inviting you to know the first brazilian site about Unity (all in portuguese):
http://www.dmu.com
And we have our Orkut group (more than 900 “unityeers”):

You are welcome !