-2

Can we connect to a database(Oracle,SQL Server) using javascript. If yes please provide me with an example.

Thanks in advace

Vinod kumar
  • 129
  • 5
  • 13

1 Answers1

2

Actually, yes you can! Not to contradict all comments saying you can't but it depends on which rights you allow the client through ActiveX and ADODB.

Example:

function dblookup()
{
    var myConnect = "Provider=Microsoft.Jet.OLEDB.4.0; Data Source=d:\\sdi.mdb"; 

    var ConnectObj = Server.CreateObject("ADODB.Connection");
    var RS = Server.CreateObject("ADODB.Recordset");
    var sql="SELECT * FROM employeespulled WHERE empid='1';";

    ConnectObj.Open (myConnect);
    RS.Open(sql,ConnectObj,adOpenForwardOnly,adLockReadOnly,adCmdText);

    var fieldCount = RS.Fields.Count;
    Response.Write ("Field Count" + fieldCount);
    RS.Close();
    ConnectObj.Close();
}

As this is an "old" way of doing things, I only recommend this in a private environment (intranet) as the security risk is pretty big.

In the modern era you would configure a webservice on the server which takes a few parameters and sends a callback function to the client. That way you take the security risk to the server and not to the client.

Tim Vermaelen
  • 6,869
  • 1
  • 25
  • 39
  • 3
    Client-side script connecting directly to a database and executing raw SQL? What could possibly go wrong? – Chris Apr 15 '14 at 10:08
  • Technically speaking, isn't this JScript rather than JavaScript? – Álvaro González Apr 15 '14 at 10:10
  • 1
    This is very specific to some particular usage of Javascript. In this example, DSN is opening MS Access database in a local file selected by pathname. If this is to be used in a website it is trying to access a database to exist on site's every visitor's local harddrive. It is furthermore requiring some system setup (for AdoDB isn't available everywhere ... e.g. smartphones, Linux, MacOS X ...) and it is requiring to disable some VERY essential security checks of every user's browser ... insane!) – Thomas Urban Apr 15 '14 at 10:18
  • 1
    I know this isn't ideal and these days there are better ways of doing this (ajax + webservice). Perhaps the OP should provide more information on what his toolset is made of. This answer is literally "yes you can and I don't care about security". – Tim Vermaelen Apr 15 '14 at 10:28