Failed to connect SQL database through Java scripts

Asked By 0 points N/A Posted on -
qa-featured

I’ve searched on how to connect SQL Database through Java scripts but I failed. I don’t know how to do it although we have a SQL server online, but I can’t find any help on the Web. I hope this time somebody could help me with my problem.

SHARE
Best Answer by Paul Mac
Answered By 0 points N/A #114513

Failed to connect SQL database through Java scripts

qa-featured

Hi friend,

To connect SQL server through java script you need a proper java script code for that. I did same thing and successfully connect with SQL server through java script. I hope these codes will help you.

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;

 

You may have to edit these codes as your own way. You need to change variable, condition, ID and table name. Also you may need to set your database name and then query with database.

Best Answer
Best Answer
Answered By 0 points N/A #114514

Failed to connect SQL database through Java scripts

qa-featured

 

Java Script is a client based scripting language which does not allow you to connect to a database.

To connect to a database we need to make use of server side scripting languages such as “asp” and “php”.

Code for connecting to ms SQL server db using php:

 

<?php
$myServer = "localhost";
$myUser = "your_name";
$myPass = "your_password";
$myDB = "examples"; 

//connection to the database
$dbhandle = mssql_connect($myServer, $myUser, $myPass)
  or die("Couldn't connect to SQL Server on $myServer"); 

//select a database to work with
$selected = mssql_select_db($myDB, $dbhandle)
  or die("Couldn't open database $myDB"); 

//declare the SQL statement that will query the database
$query = "SELECT id, name, year ";
$query .= "FROM cars ";
$query .= "WHERE name='BMW'"; 

//execute the SQL query and return records
$result = mssql_query($query);

$numRows = mssql_num_rows($result); 
echo "<h1>" . $numRows . " Row" . ($numRows == 1 ? "" : "s") . " Returned </h1>"; 

//display the results 
while($row = mssql_fetch_array($result))
{
  echo "<li>" . $row["id"] . $row["name"] . $row["year"] . "</li>";
}
//close the connection
mssql_close($dbhandle);
?>

 

Login/Register to Answer

Related Questions