开发者

Using Javascript to connect SQL Server database

I need to use Javascript to read some data from SQl Server 2008 Database. So I wrote this:(html page code)

<!DOCTYPE html "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
<title>Database Connect</title>
<script type="text/javascript">
function loadDB(){
var connection = new ActiveXObject("ADODB.Connection");

var connectionstring="Data Source=ИЛЬЯ-ПК;Initial Catalog=C:\Program Files\Microsoft SQL Server\MSSQL10.MSSQLSERVER\MSSQL\DATA\SIGMA_Database.mdf;User ID=Илья;Password="";Provider=SQLOLEDB";

connection.open(connectionstring);
var rs = new ActiveXObject("ADODB.Recordset");

rs.Open("SELECT Username FROM Users", connectio开发者_Go百科n);
rs.MoveFirst();
while(!rs.eof)
{
   document.write(rs.fields(1));
   rs.MoveNext();
}

rs.close();
connection.close();

}
</script>
</head>
<body onload="loadDB()">
<div id="main"></div>
</body>
</html>

However, nothing happens! What is wrong with it?There're some cyrillic alphabet symbols in connection string, can it be a source of problem?Or another thing is going wrong?


This is IE only code, and even in IE you have to explicitly allow such thing, see accepted answer here:
ActiveXObject in IE8


Your connectionstring is not escaped properly, it should be:

var connectionstring="Data Source=ИЛЬЯ-ПК;Initial Catalog=C:\\Program Files\\Microsoft SQL Server\\MSSQL10.MSSQLSERVER\\MSSQL\\DATA\\SIGMA_Database.mdf;User ID=Илья;Password=\"\";Provider=SQLOLEDB";


Have you tried

s.Open("SELECT Username FROM Users", connection);
rs.MoveFirst();
while(!rs.EOF)
{
   document.write(rs.Fields.Item(1));
   rs.MoveNext();
}

rs.Close();
connection.Close();

Edited rs.Fields


The problem with your codes is that you are accessing the SQL Server database using physical drive path C:\Program Files\Microsoft SQL Server\MSSQL10.MSSQLSERVER\MSSQL\DATA\SIGMA_Database.mdf;

Connect to SQL Server using the following codes

var strconnectionstring = "Data Source=your_server_name;Initial Catalog=your_database_name;User ID=database_user_id;Password=database_password;Provider=SQLOLEDB";

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜