Mapping Column Types onto Web Page Elements Adding Elements to ENUM or SET Column Definitions
9.9.6 Mapping Column Types onto Web Page Elements
Som e colum n t ypes such as ENUM and SET correspond nat urally t o elem ent s of web form s: • An ENUM has a fixed set of values from which you choose a single value. This is analogous t o a group of radio but t ons, a pop- up m enu, or a single-pick scrolling list . • A SET colum n is sim ilar, except t hat you can select m ult iple values; t his corresponds t o a group of checkboxes or a m ult iple-pick scrolling list . I f you access t he inform at ion for t hese t ypes of colum ns using SHOW COLUMNS , you can easily det erm ine t he legal values for a colum n and m ap t hem ont o t he appropriat e form elem ent aut om at ically. This allows you t o present users wit h a list of applicable values from which select ions can be m ade easily wit hout any t yping. Earlier in t his chapt er we saw how t o get ENUM and SET colum n m et adat a. The m et hods developed t here are used in Chapt er 18 , which discusses form generat ion in m ore det ail.9.9.7 Adding Elements to ENUM or SET Column Definitions
I t s really a pain t o add a new elem ent t o an ENUM or SET colum n definit ion w hen you use ALTER TABLE , because you have t o list not only t he new elem ent , but all t he exist ing elem ent s as well. One approach for doing t his using m ysqldum p and an edit or is described in Recipe 8.3 . Anot her way t o accom plish t his t ask is t o writ e your own program t hat does m ost of t he work for you by using colum n m et adat a. Let s develop a Pyt hon script add_elem ent .py t hat generat es t he appropriat e ALTER TABLE st at em ent aut om at ically when given a t able nam e, an ENUM or SET colum n nam e, and t he new elem ent value. Suppose you want t o add hot pink t o t he colors colum n of t he item t able. The current st ruct ure of t he colum n looks like t his: mysql SHOW COLUMNS FROM item LIKE colors\G 1. row Field: colors Type: setchartreuse,mauve,lime green,puce Null: YES Key: Default: puce Extra: add_elem ent .py will use t hat inform at ion t o figure out t he correct ALTER TABLE st at em ent and w r it e it out : .add_element.py item colors hot pink ALTER TABLE item MODIFY colors setchartreuse,mauve,lime green,puce,hot pink NULL DEFAULT puce; By having add_elem ent .py produce t he st at em ent as it s out put , you have t he choice of shoving it int o m ysql for im m ediat e execut ion or saving t he out put int o a file: .add_element.py item colors hot pink | mysql cookbook .add_element.py item colors hot pink stmt.sql You m ight choose t he lat t er course if you want t he new elem ent som ewhere ot her t han at t he end of t he list of values, which is where add_elem ent .py will put it . I n t his case, edit st m t .sql t o place t he elem ent where you want it , t hen execut e t he st at em ent : vi stmt.sql mysql cookbook stmt.sql The first part of t he add_elem ent .py script im port s t he requisit e m odules and checks t he com m and- line argum ent s. This is fairly st raight forward: usrbinpython add_element.py - show ALTER TABLE statement for ENUM or SET column assumes cookbook database import sys sys.path.insert 0, usrlocalapachelibpython import re import MySQLdb import Cookbook if len sys.argv = 4: print Usage: add_element.py tbl_name col_name new_element sys.exit 1 tbl_name = sys.argv[1] col_name = sys.argv[2] elt_val = sys.argv[3] Aft er connect ing t o t he MySQL server code not shown , we need t o run a SHOW COLUMNS query t o ret rieve inform at ion about t he designat ed colum n. The following code does t his, checking t o m ake sure t hat t he colum n really exist s in t he t able: cursor = conn.cursor escape SQL pattern characters in column name to match it literally esc_col_name = re.sub r[_], r\\\1, col_name this is not a use of placeholders cursor.execute SHOW COLUMNS FROM s LIKE s tbl_name, esc_col_name info = cursor.fetchone cursor.close if info == None: print Could not retrieve information for table s, column s \ tbl_name, col_name sys.exit 1 At t his point , if t he SHOW COLUMNS st at em ent succeeded, t he inform at ion produced by it is available as a t uple st ored in t he info variable. Well need t o use several elem ent s from t his t uple. The m ost im port ant is t he colum n t ype value, which provides t he enum... or set... st ring cont aining t he colum ns current definit ion. We can use t his t o verify t hat t he colum n really is an ENUM or SET , t hen add t he new elem ent t o t he st ring j ust before t he closing parent hesis. For t he colors colum n, we want t o change t his: setchartreuse,mauve,lime green,puce To t his: setchartreuse,mauve,lime green,puce,hot pink I t s also necessary t o check whet her colum n values can be NULL and what t he default value is so t hat t he program can add t he appropriat e inform at ion t o t he ALTER TABLE st at em ent . The code t hat does all t his is as follows: get column type string; make sure it begins with ENUM or SET type = info[1] if not re.match enum|set, type: print table s, column s is not an ENUM or SET tbl_name, col_name sys.exit1 add quotes, insert comma and new element just before closing paren elt_val = conn.literal elt_val type = re.sub \, , + elt_val + , type determine whether column can contain NULL values if info[2] == YES: nullable = NULL else: nullable = NOT NULL; construct DEFAULT clause add surrounding quotes unless value is NULL default = DEFAULT + conn.literal info[4] print ALTER TABLE s\n\tMODIFY s\n\ts\n\ts s; \ tbl_name, col_name, type, nullable, default That s it . You now have a working ENUM - or SET -alt ering program . St ill, add_elem ent .py is fairly basic and could be im proved in various ways: • Make sure t hat t he elem ent value youre adding t o t he colum n isnt already t here. • Allow add_elem ent .py t o t ake m ore t han one argum ent aft er t he colum n nam e and add all of t hem t o t he colum n definit ion at t he sam e t im e. • Add an opt ion t o indicat e t hat t he nam ed elem ent should be delet ed rat her t han added. • Add an opt ion t hat t ells t he script t o execut e t he ALTER TABLE st at em ent im m ediat ely rat her t han displaying it . • I f you have a version of MySQL older t han 3.22.16, it wont underst and t he MODIFY col_name synt ax used by add_elem ent .py. You m ay want t o edit t he script t o use CHANGE col_name synt ax inst ead. The follow ing t w o st at em ent s are equivalent : • ALTER TABLE tbl_name MODIFY col_name col_definition ; ALTER TABLE tbl_name CHANGE col_name col_name col_definition ; add_elem ent .py uses MODIFY because it s less confusing t han CHANGE .9.9.8 Retrieving Dates in Non-ISO Format
Parts
» O'Reilly-MySQL.Cookbook.eBook-iNTENSiTY. 4810KB Mar 29 2010 05:03:43 AM
» Introduction Using the mysql Client Program
» Problem Solution Discussion Setting Up a MySQL User Account
» Problem Solution Discussion Starting and Terminating mysql
» Problem Solution Discussion Specifying Connection Parameters by Using Option Files
» Problem Solution Discussion Mixing Command-Line and Option File Parameters
» Problem Solution Discussion What to Do if mysql Cannot Be Found
» Problem Solution Discussion Setting Environment Variables
» Problem Solution Discussion Repeating and Editing Queries
» Problem Solution Discussion Preventing Query Output from Scrolling off the Screen
» Problem Solution Discussion Specifying Arbitrary Output Column Delimiters
» Problem Solution Discussion Logging Interactive mysql Sessions
» Discussion Using mysql as a Calculator
» Writing Shell Scripts Under Unix
» Writing Shell Scripts Under Windows
» MySQL Client Application Programming Interfaces
» Perl Connecting to the MySQL Server, Selecting a Database, and Disconnecting
» PHP Connecting to the MySQL Server, Selecting a Database, and Disconnecting
» Python Connecting to the MySQL Server, Selecting a Database, and Disconnecting
» Java Connecting to the MySQL Server, Selecting a Database, and Disconnecting
» Problem Solution Discussion Checking for Errors
» Python Java Checking for Errors
» Problem Solution Discussion Writing Library Files
» Python Writing Library Files
» SQL Statement Categories Issuing Queries and Retrieving Results
» Perl Issuing Queries and Retrieving Results
» Python Issuing Queries and Retrieving Results
» Java Issuing Queries and Retrieving Results
» Problem Solution Discussion Moving Around Within a Result Set
» Problem Solution Discussion Using Prepared Statements and Placeholders in Queries
» Perl Using Prepared Statements and Placeholders in Queries
» PHP Python Java Using Prepared Statements and Placeholders in Queries
» Problem Solution Discussion Including Special Characters and NULL Values in Queries
» Perl Including Special Characters and NULL Values in Queries
» PHP Including Special Characters and NULL Values in Queries
» Python Java Including Special Characters and NULL Values in Queries
» PHP Python Java Handling NULL Values in Result Sets
» Problem Solution Discussion Writing an Object-Oriented MySQL Interface for PHP
» Class Overview Writing an Object-Oriented MySQL Interface for PHP
» Connecting and Disconnecting Writing an Object-Oriented MySQL Interface for PHP
» Error Handling Issuing Queries and Processing the Results
» Quoting and Placeholder Support
» Problem Solution Discussion Ways of Obtaining Connection Parameters
» Getting Parameters from the Command Line
» Getting Parameters from Option Files
» Conclusion and Words of Advice
» Problem Solution Discussion Avoiding Output Column Order Problems When Writing Programs
» Problem Solution Discussion Using Column Aliases to Make Programs Easier to Write
» Problem Solution Discussion Selecting a Result Set into an Existing Table
» Problem Solution Discussion Creating a Destination Table on the Fly from a Result Set
» Problem Solution Discussion Moving Records Between Tables Safely
» Problem Solution Discussion Cloning a Table Exactly
» Problem Solution Discussion Generating Unique Table Names
» Problem Solution Discussion Using TIMESTAMP Values
» Problem Solution Discussion Using ORDER BY to Sort Query Results
» Solution Discussion Working with Per-Group and Overall Summary Values Simultaneously
» Problem Solution Discussion Changing a Column Definition or Name
» Problem Solution Discussion Changing a Table Type
» Problem Solution Discussion Adding Indexes
» Introduction Obtaining and Using Metadata
» Problem Solution Discussion Perl PHP
» Problem Solution Discussion Perl
» PHP Obtaining Result Set Metadata
» Python Obtaining Result Set Metadata
» Java Obtaining Result Set Metadata
» Using Result Set Metadata to Get Table Structure
» Problem Solution Discussion Database-Independent Methods of Obtaining Table Information
» Problem Solution Discussion Displaying Column Lists Interactive Record Editing
» Mapping Column Types onto Web Page Elements Adding Elements to ENUM or SET Column Definitions
» Selecting All Except Certain Columns
» Problem Solution Discussion Listing Tables and Databases
» Problem Solution Writing Applications That Adapt to the MySQL Server Version
» Discussion Writing Applications That Adapt to the MySQL Server Version
» Problem Solution Discussion Determining Which Table Types the Server Supports
» General Import and Export Issues
» Problem Solution Discussion Importing Data with LOAD DATA and mysqlimport
» Problem Solution Discussion Specifying the Datafile Location
» Problem Solution Discussion Specifying the Datafile Format
» Problem Solution Discussion Dealing with Quotes and Special Characters
» Problem Solution Discussion Handling Duplicate Index Values
» Problem Solution Discussion Getting LOAD DATA to Cough Up More Information
» Problem Solution Discussion Dont Assume LOAD DATA Knows More than It Does
» Problem Solution Discussion Skipping Datafile Columns
» Problem Solution Discussion Exporting Query Results from MySQL
» Using the mysql Client to Export Data
» Problem Solution Discussion Exporting Tables as Raw Data
» Problem Solution Discussion Exporting Table Contents or Definitions in SQL Format
» Problem Solution Discussion Copying Tables or Databases to Another Server
» Problem Solution Discussion Writing Your Own Export Programs
» Problem Solution Discussion Converting Datafiles from One Format to Another
» Problem Solution Discussion Extracting and Rearranging Datafile Columns
» Problem Solution Discussion Validating and Transforming Data
» Writing an Input-Processing Loop Putting Common Tests in Libraries
» Problem Solution Discussion Validation by Pattern Matching
» Problem Solution Discussion Using Patterns to Match Numeric Values
» Problem Solution Discussion Using Patterns to Match Dates or Times
» See Also Using Patterns to Match Dates or Times
» Problem Solution Discussion Using Patterns to Match Email Addresses and URLs
» Problem Solution Discussion Validation Using Table Metadata
» Problem Solution Discussion Issue Individual Queries Construct a Hash from the Entire Lookup Table
» Use a Hash as a Cache of Already-Seen Lookup Values
» Problem Solution Discussion Converting Two-Digit Year Values to Four-Digit Form
» Problem Solution Discussion Performing Validity Checking on Date or Time Subparts
» Problem Solution Discussion Writing Date-Processing Utilities
» Problem Solution Discussion Performing Date Conversion Using SQL
» Problem Solution Discussion Guessing Table Structure from a Datafile
» Problem Solution Discussion A LOAD DATA Diagnostic Utility
» Problem Solution Discussion Exchanging Data Between MySQL and Microsoft Access
» Problem Solution Discussion Exchanging Data Between MySQL and Microsoft Excel
» Problem Solution Discussion Exchanging Data Between MySQL and FileMaker Pro
» Problem Solution Discussion Importing XML into MySQL
» Epilog Importing and Exporting Data
» Introduction Generating and Using Sequences
» Problem Solution Discussion Using AUTO_INCREMENT To Set Up a Sequence Column
» Problem Solution Discussion Choosing the Type for a Sequence Column
» Problem Solution Discussion Ensuring That Rows Are Renumbered in a Particular Order
» Problem Solution Discussion Managing Multiple Simultaneous AUTO_INCREMENT Values
» Problem Solution Discussion Using AUTO_INCREMENT Values to Relate Tables
» Problem Solution Discussion Generating Repeating Sequences
» Problem Solution Discussion See Also
» Performing a Related-Table Update Using Table Replacement
» Performing a Related-Table Update by Writing a Program
» Performing a Multiple-Table Delete by Writing a Program
» Problem Solution Discussion Dealing with Duplicates at Record-Creation Time
» Problem Solution Discussion Using Transactions in Perl Programs
» Problem Solution Discussion Using Transactions in Java Programs
» Problem Solution Discussion Using Alternatives to Transactions
» Grouping Statements Using Locks
» Rewriting Queries to Avoid Transactions
» Introduction Introduction to MySQL on the Web
» Problem Solution Discussion Basic Web Page Generation
» Problem Solution Discussion Using Apache to Run Web Scripts
» Problem Solution Discussion Using Tomcat to Run Web Scripts
» Installing the mcb Application
» Installing the JSTL Distribution
» Problem Solution Discussion Encoding Special Characters in Web Output
» General Encoding Principles Encoding Special Characters in Web Output
» Encoding Special Characters Using Web APIs
» Introduction Incorporating Query Results into Web Pages
» Problem Solution Discussion Creating a Navigation Index from Database Content
» Creating a Multiple-Page Navigation Index
» Problem Solution Discussion Storing Images or Other Binary Data
» Storing Images with LOAD_FILE Storing Images Using a Script
» Problem Solution Discussion Retrieving Images or Other Binary Data
» Problem Solution Discussion Serving Banner Ads
» Problem Solution Discussion Serving Query Results for Download
» Introduction Processing Web Input with MySQL
» Problem Solution Discussion Creating Forms in Scripts
» Problem Solution Discussion Creating Multiple-Pick Form Elements from Database Content
» Problem Solution Discussion Loading a Database Record into a Form
» Problem Solution Discussion Collecting Web Input
» Web Input Extraction Conventions Perl
» Problem Solution Discussion Validating Web Input
» Problem Solution Discussion Using Web Input to Construct Queries
» Problem Solution Discussion Processing File Uploads
» Perl Processing File Uploads
» Problem Solution Discussion Performing Searches and Presenting the Results
» Problem Solution Discussion Generating Previous-Page and Next-Page Links
» Paged Displays with Previous-Page and Next-Page Links
» Paged Displays with Links to Each Page
» Problem Solution Discussion Web Page Access Counting
» Problem Solution Discussion Web Page Access Logging
» Problem Solution Discussion Setting Up Database Logging
» Other Logging Issues Using MySQL for Apache Logging
» Session Management Issues Introduction
» Problem Solution Discussion Installing Apache::Session
» The Apache::Session Interface
» A Sample Application Using MySQL-Based Sessions in Perl Applications
» Problem Solution Discussion The PHP 4 Session Management Interface
» Specifying a User-Defined Storage Module
» Problem Solution Discussion Using MySQL for Session BackingStore with Tomcat
» The Servlet and JSP Session Interface A Sample JSP Session Application
Show more