1 <!DOCTYPE HTML Public "-//W3C//DTD XHTML 1.0 transitional//en" "http://www.w3.org/TR/xhtml1/DTD/ Xhtml1-transitional.dtd ">2 <HTMLxmlns= "http://www.w3.org/1999/xhtml">3 <Head>4 <title>Test JS Access database</title>5 </Head>6 <Scriptlanguage= "JavaScript"type= "Text/javascript">7 functionTestDB () {8 //To Create a database object9 varOBJdbConn= NewActiveXObject ("ADODB. Connection");Ten varstrDSN= "Driver={sql Server}; server= (local); Database=test; Uid=sa; pwd=123456"; One //Open Data Source A Objdbconn.open (STRDSN); - //database queries that execute SQL - varobjRS=Objdbconn.execute ("SELECT * from Test"); the //get number of fields - varFdcount=objRS. Fields.Count- 1; - //Check if there is a record - if (!objRS. EOF) { + document.write ("<table border=1><tr>"); - //Display the field name of the database + for (varI= 0; I<=Fdcount; I++) A document.write ("<td><b>" +objRS. Fields (i). Name+ "</b></td>"); at document.write ("</tr>"); - //displaying database content - while (!objRS. EOF) { - document.write ("<tr>"); - //Show fields for each record - for(i= 0; I<=Fdcount; I++) in document.write ("<td valign= ' top ' >" +objRS. Fields (i). Value+ "</td>"); - document.write ("</tr>"); to Objrs.movenext (); //move to the next record + } - document.write ("</table>"); the } * Else $ document.write ("There are no records in the database!<br>");Panax Notoginseng - objRS. Close (); //Close Record Collection the Objdbconn.close (); //Close Database Link + } A </Script> the + <Bodyonload= "Initdb ()"> - This is my page. $ <BR> $ <inputtype= "button"value= "Submit"onclick= "TestDB ()" /> - </Body> - </HTML>
The above code can implement JS read the database and display it in a list. Click the button to see the results.
The SQL statement executed is: SELECT * from Test.
Unfortunately, it seems that only IE support (at least IE8 can), Chrome and Firefox does not support, will be error:
uncaught referenceerror:initdb is not defined
uncaught referenceerror:activexobject is not defined The main problem is the ActiveXObject object.
Remember: ActiveX is a Microsoft thing, so this thing only ie support! links introduce ActiveXObject, you can do a lot of things: file operations, database operations, registry operations. A bit of a dangerous behavior. http://www.jsann.com/post/activexobject_in_javascript.htmlhttp://eyesinthesky.iteye.com/blog/1560033