Introduction

In this article, I will explain how to connect to a SQL database with JavaScript and how to show data from a database as a TextBox value.
Note: This program will only work with Internet Explorer.
First I created a database EmpDetail. Then I created a table in this database.
Query Code
  1. CREATE TABLE [dbo].[emp](
  2. [id] [int] NULL,
  3. [name] [varchar](50) NULL,
  4. [salary] [int] NULL
  5. ) ON [PRIMARY]
Now insert some data in the emp table.
Complete Program
Show_Record_With_TextBox_Value.htm
  1. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  2. <html xmlns="http://www.w3.org/1999/xhtml">
  3. <head>
  4. <title></title>
  5. <script type="text/javascript" >
  6. function loadDB()
  7. {
  8. var txtid = document.getElementById('txtid').value;
  9. if (txtid.length != 0) {
  10. var connection = new ActiveXObject("ADODB.Connection");
  11. var connectionstring = "Data Source=.;Initial Catalog=EmpDetail;Persist Security Info=True;User ID=sa;Password=****;Provider=SQLOLEDB";
  12. connection.Open(connectionstring);
  13. var rs = new ActiveXObject("ADODB.Recordset");
  14. rs.Open("select * from emp where id=" + txtid, connection);
  15. rs.MoveFirst();
  16. var span = document.createElement("span");
  17. span.style.color = "Blue";
  18. span.innerText = " ID " + " Name " + " Salary";
  19. document.body.appendChild(span);
  20. while (!rs.eof)
  21. {
  22. var span = document.createElement("span");
  23. span.style.color = "green";
  24. span.innerText = "\n " + rs.fields(0) + " | " + rs.fields(1) + " | " + rs.fields(2);
  25. document.body.appendChild(span);
  26. rs.MoveNext();
  27. }
  28. rs.close();
  29. connection.close();
  30. }
  31. else
  32. {
  33. alert("Please Enter Employee Id In TextBox");
  34. }
  35. }
  36. </script>
  37. <style type="text/css">
  38. #main
  39. {
  40. height: 264px;
  41. }
  42. </style>
  43. </head>
  44. <body>
  45. <div id="show" style="font-size: x-large; font-weight: bold; height: 142px; color: #009999;">
  46. Employee Details<p style="font-size: medium; color: #000000;">
  47. Enter Employee Id
  48. <input id="txtid" type="text" /></p>
  49. <p>
  50. <input id="ShowRecord" type="button" value="Show" onclick="loadDB()" /> </p>
  51. </div>
  52. </body>
  53. </html>
Output 1
1.jpg
Output 2
2.jpg
Output 3
If the TextBox value is null then:
error-image.jpg
For more information, download the attached sample application.