322

Can anybody give me some sample source code showing how to connect to a SQL Server 2005 database from JavaScript locally? I am learning web programming on my desktop.

Or do I need to use any other scripting language? Suggest some alternatives if you have them, but I am now trying to do it with JavaScript. My SQL Server is locally installed on my desktop — SQL Server Management Studio 2005 and IE7 browser.

jva
  • 2,797
  • 1
  • 26
  • 41
Enjoy coding
  • 4,268
  • 12
  • 40
  • 50

8 Answers8

787

You shouldn´t use client javascript to access databases for several reasons (bad practice, security issues, etc) but if you really want to do this, here is an example:

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; 

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.

And there are rumors of an ancient legend about the existence of server javascript, but this is another story. ;)

Fabio Vinicius Binder
  • 13,024
  • 4
  • 34
  • 33
  • 363
    Congratulations on being pretty much the only person here who actually shows that it is possible (although not recommended). – TheTXI May 13 '09 at 12:41
  • 6
    While this could work on the OP's set up - he did say he wanted to learn "web programming" - and Internet Explorer in a low security environment is not web programming. – Quentin May 13 '09 at 12:43
  • 31
    I don´t understand why this comment qualifies as a negative vote. I explain how to do it but tell him to not use it. – Fabio Vinicius Binder May 13 '09 at 12:45
  • 31
    fbinder: some people will vote this down because they think that any attempt at database connectivity and querying from JavaScript is a big no-no (even though you state that pretty clearly). If I were you, I wouldn't mind the one or two negative votes you get on this and just enjoy the numerous up votes it will receive due to it being the only answer that actually answers the question posed. – TheTXI May 13 '09 at 13:13
  • 42
    It should probably be noted, however, that this answer will probably not work for non-IE browsers due to the use of ActiveX (even though the original poster was explicit about his use of IE). – TheTXI May 13 '09 at 13:15
  • 1
    If someone is really doing this, they're probably not doing it in a *browser* as such, right? BTW, did you run the code? I'd think that `.MoveFirst`, `.movenext`, and `.close` would need `()` after them to work, and are they really case-insensitive in JS? – Kragen Javier Sitaker Mar 21 '11 at 17:10
  • 4
    I *think* you can change "User ID=;Password=;" to "integrated security=SSPI" and get better security. Hackers could still get the database and server name but I don't think that will help them much without a username and password. Anyone else have thoughts on this? – Shawn Eary Apr 14 '13 at 02:32
  • You mentioned that server side javascript is kind of unknown territory... what about popular applications like node.js? Would there be any forseeable issues going forward with using node.js on my server to get data from and manipulate mysql. – Chuck Dries Jun 26 '14 at 16:33
  • Works perfectly. Do you know however how to use Integrated Security=true instead of User ID and Password? It generates error: Multiple-step OLE DB operation generated errors – petrsyn Sep 05 '14 at 14:11
  • what is ADODB,ADODB.Recordset, rs? please give response fast – Kishan Sep 27 '14 at 12:22
  • 4
    Everyone thinks this is crazy and a bad practice, but it actually isn't. MySQL provides built a built in user privilege system. If you set it up properly, it actually gives you BETTER security and protection against SQL injection. Because you can set row-level permissions in newer versions, it's actually a very powerful programming paradigm, especially when combined with a js ORM like sequelizejs.com. r0ml gave a talk about this, essentially how to develop an app with no application layer, just direct JS to SQL access https://www.hackerschool.com/events/90 – Nick Sweeting Feb 12 '15 at 19:57
  • 1
    One should **NEVER** under any circumstance use JS to connect to a database if you absolutely must connect to a database in realtime use AJAX and make your server side script connect to the database. –  Jul 21 '15 at 07:19
  • 4
    Jdoonan: Never?? There isn't such thing. And I will give an example. What if you wanted to create a web-based ETL Tool?It has to connect to different databases and perform various actions. You would like to provide the ability for your customers to connect to any database they can access from their computers, because they will not have to put their databases public on the internet or force an entire server connect to a vpn(this last one has various issues). I believe this topic is great! And I will search around for cross-browser connection methods to different databases. – llouk Apr 11 '16 at 00:03
  • 1
    What about using this in HTAs? Where there is no server side? – corky_bantam Jun 23 '16 at 06:16
  • From another perspective, as long as you don't have write access to the database, the data is open, you trust your users to not overuse or DDos it and the service is not critical, it can be fine. In the SPARQL world that is a common scenario where you have a public SPARQL endpoint. Yes SPARQL isn't SQL but in this case it seems to be more of a mentality difference rather than a technical reason. – Konrad Höffner Nov 14 '17 at 14:25
  • I would only ever even remotely consider this on an internal network where the used account is set up read-only and only to the tables actually needed. Pretty much if you aren't comfortable publishing all the data that users who use this can see publicly (or within the network that has access), then it shouldn't be considered. But if you are ok with that then it can be a very useful tool. – Wobbles Dec 04 '17 at 18:41
  • I would be doing this from an enterprise scheduling app to write metrics on different application jobs to our data hub. – Chris Marotta Apr 27 '20 at 17:07
  • 1
    The talk by r0ml advocating in favour of a two-tier architecture (just browser and database) is available at https://www.youtube.com/watch?v=hAuV0AYzMuQ (@NickSweeting thanks a lot for referencing it!; the link is outdated though). Note that you would still use a very simple server such as Apache with https://github.com/r0ml/mod_pg or such as http://postgrest.org to serve an HTTP interface to your database, because ActiveX is not supported by modern browsers. – David Jul 10 '20 at 22:06
  • 1
    If the client where written in python, people wouldn't mind, but if it is javascript in the browser, it is bad practice. I don't get that. – Ludovic Aubert May 15 '21 at 19:25
  • I also wonder if features like Row Level Security in SQL Server where you can grant users fined grained access to specific selects, could change the game. – Ludovic Aubert May 15 '21 at 19:26
  • Nodejs is javascript and it's server side, never say never :) – WtFudgE Jul 23 '22 at 14:51
23

This would be really bad to do because sharing your connection string opens up your website to so many vulnerabilities that you can't simply patch up, you have to use a different method if you want it to be secure. Otherwise you are opening up to a huge audience to take advantage of your site.

Kev
  • 118,037
  • 53
  • 300
  • 385
allen walker
  • 361
  • 3
  • 2
  • 10
    Upvote because you actually explained why it's a bad idea – Reversed Engineer Apr 22 '16 at 14:25
  • security tips more usable and important than technical solutions – saber tabatabaee yazdi Nov 14 '16 at 12:47
  • 28
    Down vote because the OP didn't ask if it was good or bad practice, they asked how. You can insert why it may be a bad idea along an actual ANSWER, but just saying it is a bad idea doesn't deserve to be its own answer, it's a comment at best. – Wobbles Dec 04 '17 at 18:38
  • 1
    What if you're just writing something behind a secure firewall to interface with an on premises server, is this still bad? – Bryan Bryce Nov 29 '18 at 23:31
  • Correct me if I'm wrong but if the user provided is read only, and you manage which tables they can access, it is technically safe until something changes, no? I'd not advise tho either unless the entire DB contained non sensitive info. Could put sensitive info in another DB. I can imagine this being useful for a static website with no sensitive info. If need auth, could use oautj2 async on another server. – Joe Flack Oct 24 '19 at 12:12
  • The security string can be easily handled in AWS, for example. And Javascript is a language they support. Saying "this is always bad practice" is very small-minded thinking. – PRMan Jul 13 '20 at 21:32
  • 1
    Why do you have to share your connection string ? What if we are on a private network (typically intranet) and the connection string is typed in by a handfull of trusted users ? Don't leave the connection string in the source code. – Ludovic Aubert May 14 '21 at 08:29
  • Maybe this can find simple use of a isolated network that does not requre internet acces and will simplify the development process by avoiding of use of other technologies. – al1en Aug 21 '21 at 05:51
13

A perfect working code..

    <script>
    var objConnection = new ActiveXObject("adodb.connection");
    var strConn = "driver={sql server};server=QITBLRQIPL030;database=adventureworks;uid=sa;password=12345";
    objConnection.Open(strConn);
    var rs = new ActiveXObject("ADODB.Recordset");
    var strQuery = "SELECT * FROM  Person.Address";
    rs.Open(strQuery, objConnection);
    rs.MoveFirst();
    while (!rs.EOF) {
        document.write(rs.fields(0) + "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;");
        document.write(rs.fields(1) + "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;");
        document.write(rs.fields(2) + "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;    ");
        document.write(rs.fields(3) + "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;    ");
        document.write(rs.fields(4) + "<br/>");
        rs.movenext();
    }
</script>
Uthaiah
  • 1,283
  • 13
  • 14
11

Web services

SQL 2005+ supports native WebServices that you could almost use although I wouldn't suggest it, because of security risks you may face. Why did I say almost. Well Javascript is not SOAP native, so it would be a bit more complicated to actually make it. You'd have to send and receive SOAP via XmlHttpRequest. Check google for Javascript SOAP clients.

Robert Koritnik
  • 103,639
  • 52
  • 277
  • 404
6

Playing with JavaScript in an HTA I had no luck with a driver={SQL Server};... connection string, but a named DSN was OK :
I set up TestDSN and it tested OK, and then var strConn= "DSN=TestDSN"; worked, so I carried on experimenting for my in-house testing and learning purposes.

Our server has several instances running, e.g. server1\dev and server1\Test which made things slightly more tricky as I managed to waste some time forgetting to escape the \ as \\ :)
After some dead-ends with server=server1;instanceName=dev in the connection strings, I eventually got this one to work :
var strConn= "Provider=SQLOLEDB;Data Source=server1\\dev;Trusted_Connection=Yes;Initial Catalog=MyDatabase;"

Using Windows credentials rather than supplying a user/pwd, I found an interesting diversion was discovering the subtleties of Integrated Security = true v Integrated Security = SSPI v Trusted_Connection=Yes - see Difference between Integrated Security = True and Integrated Security = SSPI

Beware that RecordCount will come back as -1 if using the default adOpenForwardOnly type. If you're working with small result sets and/or don't mind the whole lot in memory at once, use rs.Open(strQuery, objConnection, 3); (3=adOpenStatic) and this gives a valid rs.RecordCount

Community
  • 1
  • 1
AjV Jsy
  • 5,799
  • 4
  • 34
  • 30
4

As stated before it shouldn't be done using client side Javascript but there's a framework for implementing what you want more securely.

Nodejs is a framework that allows you to code server connections in javascript so have a look into Nodejs and you'll probably learn a bit more about communicating with databases and grabbing data you need.

Shiri
  • 1,972
  • 7
  • 24
  • 46
3

I dont think you can connect to SQL server from client side javascripts. You need to pick up some server side language to build web applications which can interact with your database and use javascript only to make your user interface better to interact with.

you can pick up any server side scripting language based on your language preference :

  • PHP
  • ASP.Net
  • Ruby On Rails
Vikram
  • 6,865
  • 9
  • 50
  • 61
  • 1
    This was one of the only true answers I could find. What ASP.net options should I be investigating? What more in addition to microsoft drivers do I need? – Rachael Jan 28 '14 at 02:28
  • you could potentially use ADO.Net or Entity Framework / LinqToSql - any of these actually. – Vikram Jan 28 '14 at 05:07
3

(sorry, this was a more generic answer about SQL backends--I hadn't read the answer about SQL Server 2005's WebServices feature. Although, this feature is still run over HTTP rather than more directly via sockets, so essentially they've built a mini web server into the database server, so this answer is still another route you could take.)

You can also connect directly using sockets (google "javascript sockets") and by directly at this point I mean using a Flash file for this purpose, although HTML5 has Web Sockets as part of the spec which I believe let you do the same thing.

Some people cite security issues, but if you designed your database permissions correctly you should theoretically be able to access the database from any front end, including OSQL, and not have a security breach. The security issue, then, would be if you weren't connecting via SSL.

Finally, though, I'm pretty sure this is all theoretical because I don't believe any JavaScript libraries exist for handling the communications protocols for SSL or SQL Server, so unless you're willing to figure these things out yourself it'd be better to go the route of having a web server and server-side scripting language in between the browser and the database.

Kev
  • 15,899
  • 15
  • 79
  • 112
  • 2
    Well said. There is nothing wrong with accessing a database directly from a client (i.e. every thick client ever made) and not through a web service. If you use windows authentication and a good security layer there is nothin wrong with this – Nick.Mc Dec 21 '16 at 09:35