Hello coders! You might be thinking why the hell anyone wants to connect to database using client side script. Well it's obvious no one wants to do so for several reasons including security. Anyways the point is- Is it possible to connect to database using JavaScript? This interesting question was asked by an interviewer to one of my friend.
Answer is yes! we can connect our database using JavaScript. But how? Don't worry if you are not aware of such thing , here I have described the procedure.
The below script is able to connect to SQL Server database using JavaScript. Since we are using ActiveXObject, it will not run on non IE browsers.
This example uses ActiveX Data Objects (ADO). Microsoft's ActiveX Data Objects (ADO) is a set of Component Object Model (COM) objects for accessing data sources. A part of MDAC, it provides a middleware layer between programming languages and OLE DB (a means of accessing data stores, whether they be databases or otherwise, in a uniform manner).
NOTE: A better way to connect to a sql server would be to use some server side language like PHP, Java, .NET, among others. Client javascript should be used only for the interfaces.
Answer is yes! we can connect our database using JavaScript. But how? Don't worry if you are not aware of such thing , here I have described the procedure.
The below script is able to connect to SQL Server database using JavaScript. Since we are using ActiveXObject, it will not run on non IE browsers.
var connection = new ActiveXObject("ADODB.Connection") ;
var connectionstring="Data Source=<server>;Initial Catalog=<catalog>;User ID=<user>;Password=<password>;Provider=SQLOLEDB";
connection.Open(connectionstring);
var rs = new ActiveXObject("ADODB.Recordset");
rs.Open("SELECT * FROM table", connection);
rs.MoveFirst
while(!rs.eof)
{
document.write(rs.fields(1));
rs.movenext;
}
rs.close;
connection.close;
This example uses ActiveX Data Objects (ADO). Microsoft's ActiveX Data Objects (ADO) is a set of Component Object Model (COM) objects for accessing data sources. A part of MDAC, it provides a middleware layer between programming languages and OLE DB (a means of accessing data stores, whether they be databases or otherwise, in a uniform manner).
NOTE: A better way to connect to a sql server would be to use some server side language like PHP, Java, .NET, among others. Client javascript should be used only for the interfaces.
