Web services :: Associated databases ::
The next two illustrate connections to an Oracle database; for these it is necessary to specify a database username (HSimpson) and password (Doh). Other database options can be set at this stage, as in the second example which sets the database to autocommit mode (each database operation is immediately made permanent). $dbh = DBI->connect(
"dbi:Oracle:CSCI8.CS","HSimpson", "Doh");
#$dbh = DBI->connect("dbi:Oracle:CSCI8.CS",
# "Hsimpson", "Doh", { AutoCommit => 1} );
In Java you would ask a java.sql.Connection object to return a statement object; you would then use this to submit strings with SQL queries. Perl is very similar. You get statement handles from your database handle, and then execute the statement. The code fragment below would attempt to return all data in Table1 of the database referenced by your $dbh handle. $sth = $dbh->prepare("SELECT * FROM Table1");
$sth->execute;
You could be more selective: $sth = $dbh->prepare("SELECT * FROM Table1 WHERE GRADE > 3");
$sth->execute;
Often you will want queries that depend on data entered by the user. You can employ interpolation when building a query string: print "Enter Grade cutoff : ";
$grade = <STDIN>;
chomp($grade);
$sth = $dbh->prepare("SELECT * FROM Table1 WHERE GRADE > $grade");
...
$sth->execute;
Usually it is better to prepare statements with placeholders for arguments, rather than building a specific query each time: # prepare the statement immediately after opening the database connection.
$sth = $dbh->prepare("SELECT * FROM Table1 WHERE GRADE > ? ");
# do other work
...
print "Enter Grade cutoff : ";
$grade = <STDIN>;
chomp($grade);
# invoke the query, with the value of $grade substituted
# for the first (?) placeholder
$sth->execute($grade);
The ‘prepare’ step involves some parsing of the SQL string, and this is relatively costly. So it is more efficient to prepare the statement once, and later bind values to placeholders, rather than create a new SQL query string for each request and then parse that string. A secondary reason for using prepared statements is that they help avoid messy problems with quoted strings. Suppose you need a query like the following: $sth = $dbh->prepare("SELECT GRADE FROM Table1 WHERE NAME='Smith'");
Single string quotes are required around string data in an SQL statement, so you need NAME='Smith'. Usually, the name will be data entered: print "Enter name : ";
$name= <STDIN>;
chomp($name);
$sth = $dbh->prepare("SELECT * FROM Table1 WHERE GRADE > '$name'');
The value entered for the name is interpolated into the doubly quoted string with the SQL statement; SQL requires the value to be surrounded by single quote characters. Problems appear with customer names such as O’Brien – the single quote character in the name disrupts the pairing of quotes and results in an error from the SQL system. This problem does not occur if you use ‘?’ placeholders and bind values to the placeholders. In addition to ‘select’ statements for data retrieval, you will need ‘insert’, ‘update’, and ‘delete’ statements like the following: $sth = $dbh->prepare("INSERT INTO TABLE1 VALUES (?, ?, ?)");
$sth = $dbh->prepare("UPDATE TABLE SET GRADE= ? WHERE NAME = ?");
$sth = $dbh->prepare("DELETE FROM TABLE1 WHERE NAME='Smith'");
If your SQL is faulty, the prepare operation will fail and you get undef as the result: $sth = $dbh->prepare(...); unless defined $sth die "SQL problem"; Correctly formed SQL statements may fail; for example, you will get an SQL error if you attempt to insert a new record with a primary key that fails a uniqueness test. The DBI module variable $DBI::errstr contains an error report if an operation failed. This can be included in any termination message: $sth->execute($data) || die "delete failed because $DBI::errstr"; Data retrieved by an SQL select query are accessed via the statement handle; this can be used to retrieve successive rows of the results table: @row = $sth->fetchrow_array; The fetchrow_array method returns undef when have all data have been processed. The typical code pattern for data retrieval is: $sth = $dbh->prepare("select ... = ?");
...
$sth->execute($data1, $data2);
while(@row = $sth->fetchrow_array) {
...
}
All database handles are closed at program termination. However, you should close database connections as soon as possible: $dbh->close; Database drivers often rely on environment variables. For example, a Unix version of the Oracle driver relies on environment variables to hold information identifying the directories containing Oracle components, version number and related data. You will need to consult your database documentation to find exactly what environment variables must be defined. Usually, you define and ‘export’ these variables from a ‘.profile’ file (a kind of Unix equivalent to a ‘batch’ file that is run whenever you log in). If the environment variables are not set correctly, you will not be able to connect to your database. |
legal disclaimer
Our website is not responsible for the information contained by this article. Web-articles is a free articles resource.
Suggestion: If you need fresh, daily updated content for your website, feel free to use our service. Click here for more information.
related articles
As you begin to blog and appreciate the complexities, benefits, and potential offshoots of blogging, you will undoubtedly begin to wonder how to get your employees to blog. The first step is to realize that it’s entirely likely that some of your employees are already blogging. With millions of blogs in the world, assuming that none of your employees is blogging is about as naive as assuming that none of your employees has ever downloaded music online it could be true, but the odds d...
Internal employee blogs can be a fantastic catalyst within your company. Internal employee blogs help forge connections inside the company. External employee blogs are also great because they allow employees to connect with like-minded individuals outside the company. It doesn’t matter whether you have a dozen employees or 2000, having your staff members connect creates fantastic new opportunities especially if you’re using idea blogs, as these pairings ...
3. The vBulletin Administrator Experience
The vBulletin Administrator Experience What are the differences for an administrator compared to a regular member? Well, there are quite a few. We'll take a look at some of the more important ones now. Forum and Thread Tools The first differences are the forum and thread tools. Forum tools allow the administrator to view the posts and attachments that are in the moderator queue. (These are the posts and attachments that need to be approved before being made visible.) Th...
4. Generation of dynamic pages
Most of this text is concerned with elaborate ways of creating dynamic pages through Perl scripts, PHP scripts, Java servlets and Java Server Pages. The basic Apache setup provides support for CGI programs (based on Perl scripts and alternatives), and for the fairly limited ‘server-side includes’ (SSI) mechanism. The relevant modules (mod_env, mod_cgi and mod_include) are included in the default Apache build. It is best to limit the number of directories that contain executable code that can generate dynamic pages. The...
5. Apache logs
Apache expects to maintain logs recording its work. In its standard configuration, Apache records all access attempts by clients and all server-side errors (subject to a minimum severity cutoff that is set by a control parameter). There is further provision for creation of custom logs. For example, you can arrange to log data identifying the browsers used (so, if you really want to know, you can find the proportions of your clients who use Opera, Netscape, IE or another browser). You should plan how to use the data from these ...
6. The next few elements define options
In this example, the defaults for htdocs and its subdirectories are set to allow clients to view the contents of a directory (as a page with a list of files, or something prettier), enable support for content negotiation, and permit the use of Unix inter-directory links. The next subdirective, AllowOverride, makes provision for overriding .htaccess files in subdirectories. The options here allow you to specify that nothing be changed (as in the example with AllowOverride None), or that anything be changed (AllowOverride Any...
7. The configuration file
If you are running your own Linux system, you can install Apache as a standard httpd daemon server that will use port 80. (You have to do the installation when logged in as the system’s administrator – root account.) You will need to create user and group accounts for your web server (as described in your Linux manuals); the usernames ‘www’ or ‘nobody’ are conventional. The user entry that you create in your /etc/password file should be appropriate for a server – no password (so it is ...