8.
Database connecting
Before a database can be accessed from a SWFKit
app, a database connection has to be established.
The steps to make a database connection
1. Creating an ADO.Connection object
| var conn = new ActiveXObject("ADODB.Connection"); |
2. Creating a connection string and open the
connection
The connection string contains the provider,
db name, etc. E.g. To connect to a MS Access
DB "c:\mydata\sample.mdb", the connection
string is
var connStr = "Provider=Microsoft.Jet.OLEDB.4.0;Data
Source=c:\mydata\sample.mdb";
conn.open(connStr); |
To connect to a MS SQL SERVER DB "Northwind"
on server "mysite", the connection
string is
var connStr = "Provider=SQLOLEDB;Server=mysite;Database=Northwind;User
Id=MyId;Password=123aBc";
conn.open(connStr); |
SWFKit can connect to any database like VB,
Delphi, VC or ASP can do.
How to ensure the connection has been made
successfully? You can handle the "ConnectComplete"
event of the ADO.Connection object. The event
fires when the connection is completed.
var conn = new ActiveXObject("ADODB.Connection");
conn.connectOK = false;
conn.ConnectComplete = function (err, status,
cnt)
{
if (typeof err != "undefined")
{
trace(err.Description);
return;
}
else
{
trace("Connect complete!");
conn.connectOK = true;
}
trace("status: ", status.value);
}
var connStr = "Provider=Microsoft.Jet.OLEDB.4.0;Data
Source=c:\mydata\sample.mdb";
conn.open(connStr);
if (!conn.connectOK)
{
trace("Failed to connect to the DB");
return;
} |
After the connection has been made, you can
get data from database using the ADO.Recordset
object.
1. Creating the ADO.Recordset object
| var record = new ActiveXObject("ADODB.Recordset"); |
2. Opening the ADO.Recordset object with a
specified command string
| record.Open("select id, name, age,
sex, score from student", conn, /*adOpenKeyset*/1,
/*adLockPessimistic*/2); |
3. Moving to the start of the record set
4. Fetching Data
while (!record.eof)
{
trace(record.Fields(0).Value.toString());
trace(record.Fields(1).Value.toString());
trace(record.Fields(2).Value.toString());
trace(record.Fields(3).Value.toString());
trace(record.Fields(4).Value.toString());
record.moveNext();
} |
1. Move to the start of the record set
2. Move to the end of the record set
3. Move to the previous record
record.MovePrevious();
if (record.bof()) record.MoveFirst(); |
4. Move to the next record
record.MoveNext();
if (record.eof) record.MoveLast(); |
Microsoft
MSDN ADO Reference
ADO
Tutorial
|