Stopbyte

What's the best way connect to SQL Server database from JavaScript?

Hi,

I’ve been wondering what is the best way to connect to a SQL Server database using Javascript (from within javascript).

i know it can be done easily from the server backend, using PhP, Python, NodeJs or something else.

but i am new to this web whole thing and i am trying to learn all aspects of Javascript.

any help will be really appreciated.

I highly suggest that you don’t do it. connecting to a SQL server database using javascript client side code i guess it’s possible (though i never thought about it how!!) but mainly doing so will cause for your Website to be open to so much vulnerabilities and security flaws. doing so will mean that you are giving everyone in the web Password and username to your database.

1 Like

As other guys said in the comments, you really should not do this. but if you insist (for learning purposes) you may try the following example:

// STEP 1: Initialize a new ActiveXObject for the SQL Server connection.
var connection = new ActiveXObject("ADODB.Connection") ;
 
// Your connection string: and this is the reason why you shouldn't do this
// in live website, "everyone has access to this connection string".
// replace the values within "<>" to your values.
var your_connection_string = "Data Source=<SQL Server (IP or host)>;Initial Catalog=<your catalog (a.k.a Database)>;User ID=<your username>;Password=<your password>;Provider=SQLOLEDB";
 
// STEP 2: Now open the connection using the connection string above.
connection.Open(your_connection_string);
 
// STEP 3: Initialize a new activeX object, this time for a recordset,
// so we can read data from database.
var rs = new ActiveXObject("ADODB.Recordset");
 
// STEP 4: Manipulate your data the way you want.
rs.Open("SELECT * FROM <your table>", connection);
rs.MoveFirst
while(!rs.eof)
{
    document.write(rs.fields(1));
    rs.movenext;
}
 
// STEP 5: be nice and Finalize the recordset and the connection.
rs.close;
connection.close;

It’s really recommended that you use Server side backend to Access your database and secured files using something like the platforms you mentioned in your question (NodeJS, PhP, Asp.NET,…etc).

That example is given AS IT IS, you are free to use it anyway you want at your own Risk. I am not responsible to any damage it can bring.

have a nice day.

1 Like