Perl connection to access database
The prefix is that ActivePerl (505 or above) and MS Access 97 must be installed.
1. Install the Win32-ODBC Module
Step 1:
Download win32-odbc.zip from the toolsbar and use WinZip to unbind it to a temp directory. There are three files in total:
Readme
Win32-ODBC.ppd
Win32-ODBC.tar.gz
Step 2:
In the DOS window, run the following doscommand In the temp directory:
PPM install Win32-ODBC.ppd
2. Prepare the database for testing (ACCESS)
Step 1:
Start MS Access and create a new empty database named odbctest. mdb, Which is saved in a directory (remember the path ).
Step 2:
Create a new table and create three fields:
Field Name Data Type
Name: 50 characters in length
Email character, length 50
Age number, long integer
Save the table as address (note that no ID is automatically added in this example). Enter several records:
Nihthawk nighthawk@163.net 20 1234567
John jt@163.net 24 0284393293
Kit kit@21cn.com 18 3948932
After saving, close the database file.
Step 3:
Open the ODBC Data Source (32-bit) in the control panel, find the user data source list in the user DSN column, and select a row named "MS Access 97 Database, then press the "Configure" key.
In the database box, press "Select...", select the database file odbctest. mdb created in Step 1.2, and press OK. All other items in ODBC settings use the default settings, and then OK. OK. Close the dialog window.
3. Now the database is ready for use. Let's test it:
#! /Usr/bin/perl
Use Win32: ODBC;
$ DSN = "MS Access 97 Database ";
$ DBASE = "access. mdb ";
# Connecting to a database
If (! ($ Db = new Win32: ODBC ($ DSN ))){
Print "failed to connect to database./N ";
Exit ();
}
Else {
Print "succeeded in connecting to the database (connection number:", $ db-> connection (), ")/n ";
}
# Tables in the database
Print "tables in the database :";
@ Tables = $ db-> tablelist;
Print @ tables;
Print "/N ";
# Selecting a data table
If (! $ Db-> SQL ("select * from [address] where age> = 20 ")){
@ Fieldnames = $ db-> fieldnames ();
$ Cols =$ # fieldnames + 1;
# Number of fields in the table
Print "Table address field count: $ Cols/N ";
# Field List
For ($ I = 0; $ I <$ Cols; $ I ++ ){
Print "$ fieldnames [$ I]/t ";
}
Print "/N ";
# List records older than 20
While ($ db-> fetchrow ()){
@ Values = $ db-> data ();
Print @ values;
Print "/N ";
}
}
##### SQL #########
# Add record
$ Sqlinsert = "insert into address values ('olo', 'euler/@ 21cn.com ', 28, '021-345689 ')";
# Update records
$ Sqlupdate = "Update address set age = age + 10 ";
# Deleting records
$ Sqldelete = "delete from address where name = 'jimtyany '";
$ Rc = $ db-> SQL ($ sqlinsert );
Die QQ (SQL failure "$ sqlinsert":), $ db-> error (), QQ (/n) If $ RC;
$ Rc = $ db-> SQL ($ sqlupdate );
Die QQ (SQL failure "$ sqlupdate":), $ db-> error (), QQ (/n) If $ RC;
$ Rc = $ db-> SQL ($ sqldelete );
Die QQ (SQL failure "$ sqldelete":), $ db-> error (), QQ (/n) If $ RC;
# Close the link
$ Db-> close ();