mirror of
https://github.com/PyMySQL/mysqlclient.git
synced 2025-08-15 11:10:58 +08:00
Some user-contributed examples.
This commit is contained in:
257
mysql/examples/dbtrainer0
Normal file
257
mysql/examples/dbtrainer0
Normal file
@ -0,0 +1,257 @@
|
||||
#!/usr/bin/python
|
||||
# TITLE: dbtrainer0
|
||||
# WRITTEN BY: Bradley Stec, July 1999
|
||||
# RuleSpace, Inc.
|
||||
# SUPPORTS: WebOps Database Interface Trainer Script
|
||||
# PURPOSE: This script is an code and output example of how to use the
|
||||
# MySQLdb API to communicate with a database and perform basic
|
||||
# SQL queries.
|
||||
# FUNCTION: Both by executing the script and by reading the source code,
|
||||
# a programmer should be able to get a grasp on how the interface
|
||||
# works and may borrow code for their own script projects.
|
||||
# REQUIREMENTS: This script requires the access to the webops module, and that a
|
||||
# database named "TEST" be installed in the webops specified
|
||||
# database server. The contents of the test database can be created
|
||||
# using the following SQL command sets.
|
||||
#
|
||||
# CREATE TABLE COLORS (
|
||||
# COLOR varchar(32) DEFAULT '' NOT NULL,
|
||||
# PRIME_COLOR enum('No','Yes') DEFAULT 'No' NOT NULL,
|
||||
# LAST_DATE timestamp(14) DEFAULT '' NOT NULL,
|
||||
# OPEN_DATE timestamp(14) DEFAULT '' NOT NULL,
|
||||
# PRIMARY KEY (COLOR),
|
||||
# KEY PRIME_COLOR (PRIME_COLOR),
|
||||
# KEY LAST_DATE (LAST_DATE),
|
||||
# KEY OPEN_DATE (OPEN_DATE)
|
||||
# );
|
||||
#
|
||||
# INSERT INTO COLORS VALUES ('red','Yes',NOW(),NOW());
|
||||
# INSERT INTO COLORS VALUES ('blue','Yes',NOW(),NOW());
|
||||
# INSERT INTO COLORS VALUES ('green','Yes',NOW(),NOW());
|
||||
# INSERT INTO COLORS VALUES ('yellow','No',NOW(),NOW());
|
||||
# INSERT INTO COLORS VALUES ('orange','No',NOW(),NOW());
|
||||
# INSERT INTO COLORS VALUES ('purple','No',NOW(),NOW());
|
||||
# INSERT INTO COLORS VALUES ('cyan','No',NOW(),NOW());
|
||||
#
|
||||
# CREATE TABLE TEAM (
|
||||
# MEMBER_ID int(11) DEFAULT '0' NOT NULL auto_increment,
|
||||
# FIRST_NAME varchar(32) DEFAULT '' NOT NULL,
|
||||
# LAST_NAME varchar(32) DEFAULT '' NOT NULL,
|
||||
# REMARK varchar(64) DEFAULT '' NOT NULL,
|
||||
# FAV_COLOR varchar(32) DEFAULT '' NOT NULL,
|
||||
# LAST_DATE timestamp(14) DEFAULT '' NOT NULL,
|
||||
# OPEN_DATE timestamp(14) DEFAULT '' NOT NULL,
|
||||
# PRIMARY KEY (MEMBER_ID),
|
||||
# KEY FAV_COLOR (FAV_COLOR),
|
||||
# KEY LAST_DATE (LAST_DATE),
|
||||
# KEY OPEN_DATE (OPEN_DATE)
|
||||
# );
|
||||
#
|
||||
# INSERT INTO TEAM VALUES (1,'Brad','Stec','Techno Needy','aquamarine',NOW(),NOW());
|
||||
# INSERT INTO TEAM VALUES (2,'Nick','Borders','Meticulous Nick','blue',NOW(),NOW());
|
||||
# INSERT INTO TEAM VALUES (3,'Brittney','McChristy','The Data Diva','blue',NOW(),NOW());
|
||||
# INSERT INTO TEAM VALUES (4,'Fuzzy','Logic','The Logic Bunny','cyan',NOW(),NOW());
|
||||
#
|
||||
# CHANGES: 7/99 Initial Version
|
||||
|
||||
import sys
|
||||
import webops
|
||||
import traceback
|
||||
sys.stderr = sys.stdout
|
||||
|
||||
# Set Up Page Layout
|
||||
print "content-type: text/html"
|
||||
print
|
||||
print "<HTML>\n"
|
||||
print "<BODY BGCOLOR=\"#FFFFFF\">\n"
|
||||
print "<FONT FACE=\"arial\" SIZE=\"3\"><B>RuleSpace, Inc. WebOps Database Interface Trainer - Part 0</B><BR><HR>"
|
||||
print "The purpose of this page is to present sample code for interfacing with the databases within the Web Operations server farm. The display below illustrates real database queries as well as how the information is handled and presented.<P>"
|
||||
print "By viewing the CGI script which presents the information below you'll be able to see how the database interface and API works within the WebOps scripting environment.<P>"
|
||||
print "<HR>"
|
||||
|
||||
# Loading The API Support
|
||||
# The API MySQLdb is a thin wrapper around a C program which is also in the site-packages directory called _mysqlmodule.so
|
||||
# The API follows the Python Database API Spec version 2.0 which basically sets standards for what kind of methods will be
|
||||
# used to access databases within the Python environment. The _mysqlmodule.so and MySQLdb.py programs allow a programmer
|
||||
# to pass SQL commands/queries through to a database. The database server may be remote or local. The MySQL database server
|
||||
# software doesn't provide an interactive cursor, so the API programs create a "cursor" in local memory. Read the Python
|
||||
# Database API Spec version 2.0 for details.
|
||||
|
||||
# This command loads the support files
|
||||
import MySQLdb
|
||||
|
||||
# PREPARE TO CONNECT TO DATABASE
|
||||
# This command forms a connection through the support files to the target database server and database name.
|
||||
try:
|
||||
WebOpsDB = MySQLdb.Connection(host=webops.dbserver,user=webops.dbuser,passwd=webops.dbpass,db='test',port=3306,unix_socket="")
|
||||
except:
|
||||
print "\n\n<PRE>"
|
||||
traceback.print_exc()
|
||||
sys.exit()
|
||||
|
||||
# A LITTLE BONUS INFORMATION FROM THE API
|
||||
# The API can provide some information about the connection and server. Note that these functions are
|
||||
# making use of the "db" object which is a sub-class of the WebOpsDB object. The "db" object bypasses the "wrapper"
|
||||
# level of the MySQLdb interface and speaks directly to the C coded _mysqlmodule.so, therefore it is not recommended
|
||||
# that you use this method frequently in timing-sensitive script applications.
|
||||
print "<B>CONNECTED TO</B><BR>"
|
||||
print " server <B> ", WebOpsDB.db.get_host_info(), "</B><BR>"
|
||||
print " running <B>mySQL server v", WebOpsDB.db.get_server_info(), "</B><BR>"
|
||||
print " current status: ",WebOpsDB.db.stat(), "<P>"
|
||||
print "<HR>"
|
||||
|
||||
# CREATE YOUR PERSONAL CONNECTION TO THE "RESULTS" WITHIN THE CONNECTION OBJECT
|
||||
# We haven't actually queried anything yet, so don't get confused, we're just preparing for it.
|
||||
# A cursor is a "result set" holding object. The API creates a "cursor" object complete with a set of
|
||||
# methods for executing query results into it.
|
||||
try:
|
||||
cursor = WebOpsDB.cursor()
|
||||
except:
|
||||
print "\n\n<PRE>"
|
||||
traceback.print_exc()
|
||||
sys.exit()
|
||||
|
||||
# PERFORM A QUERY
|
||||
# The cursor object is a Python class object. In it, we can specify a query. Below we query the TEAM table from the
|
||||
# WebOpsDB object by referring to our new "cursor" object.
|
||||
try:
|
||||
cursor.execute("SELECT * FROM TEAM")
|
||||
except:
|
||||
print "\n\n<PRE>"
|
||||
traceback.print_exc()
|
||||
sys.exit()
|
||||
|
||||
# STORE THE RESULTS INTO A LOCALLY CONTROLLED MEMORY LOCATION
|
||||
# Two things just came from our query: 1) a description of the table structure and 2) a result set stored in the API cursor.
|
||||
# The API "cursor" must be "consumed" by your script to get the results out. Therefore its a good idea to store the results
|
||||
# into a local variable. The results will become a nicely formatted Python list data type. If you don't store it locally,
|
||||
# you'll need to requery the database every time you need the data again.
|
||||
|
||||
# 1) THE TABLE STRUCTURE
|
||||
# The cursor.description attribute will provide a Python list data type representation of the field structure.
|
||||
# In the example below we use the for loop to travel through the list and read the first element of each list.
|
||||
|
||||
# 2) THE RESULT SET
|
||||
# The result set can be completely fetched into one list data type.
|
||||
try:
|
||||
resultSet = cursor.fetchall()
|
||||
except:
|
||||
print "\n\n<PRE>"
|
||||
traceback.print_exc()
|
||||
sys.exit()
|
||||
|
||||
# AND NOW YOU CAN SEE RESULTS
|
||||
# Now you can take your information and present it.
|
||||
print "<B>EXAMPLES OF USING THE <U>SELECT</U> SQL COMMAND.</B><P>"
|
||||
print "QUERY OF TEAM TABLE<BR>"
|
||||
print "<FONT SIZE=\"1\"><B>("
|
||||
# The Table Field Names
|
||||
for cursorFieldname in cursor.description:
|
||||
print cursorFieldname[0]+","
|
||||
print ")</B>"
|
||||
print "<BR>"
|
||||
# The Result Set
|
||||
for cursorRecord in resultSet:
|
||||
print cursorRecord
|
||||
print "<BR>"
|
||||
print "<P></FONT>"
|
||||
|
||||
print "<FONT SIZE=\"1\">same results in very nicely formatted columns:<BR>"
|
||||
print "<TABLE BORDER=\"1\"><TR>"
|
||||
for cursorFieldname in cursor.description:
|
||||
print "<TD><CENTER><FONT FACE=\"arial\" SIZE=\"2\">" +cursorFieldname[0]+ "</FONT></CENTER></TD>"
|
||||
print "</TR>"
|
||||
for cursorRecord in resultSet:
|
||||
print "<TR>"
|
||||
for cursorField in cursorRecord:
|
||||
print "<TD><FONT FACE=\"arial\" SIZE=\"1\">"
|
||||
print cursorField
|
||||
print "</FONT></TD>"
|
||||
print "</TR>"
|
||||
print "</TABLE>"
|
||||
print "</CENTER>"
|
||||
print " <P></FONT><P><HR><P>"
|
||||
|
||||
# HERE'S ANOTHER TABLE
|
||||
try:
|
||||
cursor.execute("SELECT * FROM COLORS")
|
||||
except:
|
||||
print "\n\n<PRE>"
|
||||
traceback.print_exc()
|
||||
sys.exit()
|
||||
|
||||
print "QUERY OF COLORS TABLE<BR>"
|
||||
print "<FONT SIZE=\"1\"><B>("
|
||||
for cursorFieldname in cursor.description:
|
||||
print cursorFieldname[0]+","
|
||||
print ")</B>"
|
||||
print "<BR>"
|
||||
# The values are loaded into the object 'resultSet'
|
||||
resultSet = cursor.fetchall()
|
||||
for cursorRecord in resultSet:
|
||||
print cursorRecord
|
||||
print "<BR>"
|
||||
print " <BR></FONT>"
|
||||
|
||||
# Display Query Results In Columns
|
||||
print "<FONT SIZE=\"1\">same results in very nicely formatted columns:<BR>"
|
||||
print "<TABLE BORDER=\"1\"><TR>"
|
||||
for cursorFieldname in cursor.description:
|
||||
print "<TD><CENTER><FONT FACE=\"arial\" SIZE=\"1\">" +cursorFieldname[0]+ "</FONT></CENTER></TD>"
|
||||
print "</TR>"
|
||||
for cursorRecord in resultSet:
|
||||
print "<TR>"
|
||||
for cursorField in cursorRecord:
|
||||
print "<TD><FONT FACE=\"arial\" SIZE=\"1\">"
|
||||
print cursorField
|
||||
print "</FONT></TD>"
|
||||
print "</TR>"
|
||||
print "</TABLE>"
|
||||
print "</CENTER>"
|
||||
print " <P><HR><P></FONT>"
|
||||
|
||||
# NOW WE CAN SEE HOW TO COMBINE KEYED TABLES
|
||||
# The following query uses standard SQL commands to join the two databases together and produce a list of each of the team's
|
||||
# favorite colors.
|
||||
try:
|
||||
cursor.execute("SELECT TEAM.FIRST_NAME,TEAM.LAST_NAME,TEAM.FAV_COLOR,COLORS.PRIME_COLOR FROM TEAM,COLORS WHERE TEAM.FAV_COLOR = COLORS.COLOR")
|
||||
except:
|
||||
print "\n\n<PRE>"
|
||||
traceback.print_exc()
|
||||
sys.exit()
|
||||
|
||||
print "JOINED QUERY OF TEAM AND COLORS TABLES<BR>"
|
||||
print "Now we can compare our team membership list to our colors table to determine which of their favorite colors are primary colors. Notice that records in the TEAM list that don't have a \"known\" color don't show up in the results.<P>"
|
||||
print "<FONT SIZE=\"1\">results of query<BR>"
|
||||
resultSet = cursor.fetchall()
|
||||
print "<TABLE BORDER=\"1\"><TR>"
|
||||
for cursorFieldname in cursor.description:
|
||||
print "<TD><CENTER><FONT FACE=\"arial\" SIZE=\"1\">" +cursorFieldname[0]+ "</FONT></CENTER></TD>"
|
||||
print "</TR>"
|
||||
print "</TR>"
|
||||
for cursorRecord in resultSet:
|
||||
print "<TR>"
|
||||
for cursorField in cursorRecord:
|
||||
print "<TD><FONT FACE=\"arial\" SIZE=\"1\">"
|
||||
print cursorField
|
||||
print "</FONT></TD>"
|
||||
print "</TR>"
|
||||
print "</TABLE>"
|
||||
print "</CENTER>"
|
||||
print "<P>"
|
||||
|
||||
# CLOSING THE DATABASE OBJECT
|
||||
try:
|
||||
WebOpsDB.close()
|
||||
except:
|
||||
print "\n\n<PRE>"
|
||||
traceback.print_exc()
|
||||
sys.exit()
|
||||
|
||||
# CONTINUED IN DBTRAINER1
|
||||
# To learn more about inserting records, and performing other SQL functions review
|
||||
# dbtrainer1.
|
||||
|
||||
# END YOUR HTML PAGE
|
||||
print "</FONT></BODY>\n"
|
||||
print "</HTML>\n"
|
157
mysql/examples/dbtrainer1
Normal file
157
mysql/examples/dbtrainer1
Normal file
@ -0,0 +1,157 @@
|
||||
#!/usr/bin/python
|
||||
# TITLE: dbtrainer1
|
||||
# WRITTEN BY: Bradley Stec, July 1999
|
||||
# RuleSpace, Inc.
|
||||
# SUPPORTS: WebOps Database Interface Trainer Script
|
||||
# PURPOSE: This script is a code and output example of how to use the
|
||||
# MySQLdb API to communicate to a database and perform basic
|
||||
# SQL command language requests.
|
||||
# FUNCTION: Both by executing the script and by reading the source code,
|
||||
# a programmer should be able to get a grasp on how the interface
|
||||
# works and may borrow code for their own script projects.
|
||||
# REQUIREMENTS: This script requires the access to the webops module, and that a
|
||||
# database named "TEST" be installed in the webops specified
|
||||
# database server.
|
||||
#
|
||||
# CHANGES: 7/99 Initial Version
|
||||
|
||||
import sys
|
||||
import webops
|
||||
import traceback
|
||||
sys.stderr = sys.stdout
|
||||
|
||||
# Set Up Page Layout
|
||||
print "content-type: text/html"
|
||||
print
|
||||
print "<HTML>\n"
|
||||
print "<BODY BGCOLOR=\"#FFFFFF\">\n"
|
||||
print "<FONT FACE=\"arial\" SIZE=\"3\"><B>RuleSpace, Inc. WebOps Database Interface Trainer -- Part 1</B><BR><HR>"
|
||||
print "The purpose of this page is to present sample code for interfacing with the databases within the Web Operations server farm. The display below illustrates real database queries as well as how the information is handled and presented.<P>"
|
||||
print "By viewing the CGI script which presents the information below you'll be able to see how the database interface and API works within the WebOps scripting environment.<P>"
|
||||
print "<HR>"
|
||||
|
||||
# Loading The API Support
|
||||
# The API MySQLdb is a thin wrapper around a C program which is also in the site-packages directory called _mysqlmodule.so
|
||||
# The API follows the Python Database API Spec version 2.0 which basically sets standards for what kind of methods will be
|
||||
# used to access databases within the Python environment. The _mysqlmodule.so and MySQLdb.py programs allow a programmer
|
||||
# to pass SQL commands/queries through to a database. The database server may be remote or local. The MySQL database server
|
||||
# software doesn't provide an interactive cursor, so the API programs create a "cursor" in local memory. Read the Python
|
||||
# Database API Spec version 2.0 for details.
|
||||
|
||||
# This command loads the support files
|
||||
import MySQLdb
|
||||
|
||||
# PREPARE TO CONNECT TO DATABASE
|
||||
# This command forms a connection through the support files to the target database server and database name.
|
||||
try:
|
||||
WebOpsDB = MySQLdb.Connection(host=webops.dbserver,user=webops.dbuser,passwd=webops.dbpass,db='test',port=3306,unix_socket="")
|
||||
except:
|
||||
print "\n\n<PRE>"
|
||||
traceback.print_exc()
|
||||
sys.exit()
|
||||
|
||||
# A LITTLE BONUS INFORMATION FROM THE API
|
||||
# The API can provide some information about the connection and server. Note that these functions are
|
||||
# making use of the "db" object which is a sub-class of the WebOpsDB object. The "db" object bypasses the "wrapper"
|
||||
# level of the MySQLdb interface and speaks directly to the C coded _mysqlmodule.so, therefore it is not recommended
|
||||
# that you use this method frequently in timing-sensitive script applications.
|
||||
print "<B>CONNECTED TO</B><BR>"
|
||||
print " server <B> ", WebOpsDB.db.get_host_info(), "</B><BR>"
|
||||
print " running <B>mySQL server v", WebOpsDB.db.get_server_info(), "</B><BR>"
|
||||
print " current status: ",WebOpsDB.db.stat(), "<P>"
|
||||
print "<HR>"
|
||||
|
||||
# CREATE YOUR PERSONAL CONNECTION TO THE "RESULTS" WITHIN THE CONNECTION OBJECT
|
||||
# We haven't actually queried anything yet, so don't get confused, we're just preparing for it.
|
||||
try:
|
||||
cursor = WebOpsDB.cursor()
|
||||
except:
|
||||
print "\n\n<PRE>"
|
||||
traceback.print_exc()
|
||||
sys.exit()
|
||||
|
||||
# EXAMPLE: INSERTING A NEW RECORD
|
||||
# This example uses a query command to INSERT a new record into the table. The format of the data must exactly match
|
||||
# the table structure requirements or it will be rejected. Note that we are using single quotes around strings within
|
||||
# the SQL command.
|
||||
|
||||
# GOTCHA #1: The MySQLdb API doesn't respond well to zero value datatime fields. Make sure that you populate your datetime
|
||||
# fields with positive values. You'll notice I used the built-in mySQL function NOW() to make sure that there was a valid
|
||||
# date in the created field. The modified field is auto-updated because it is the first timestamp data type in the data table.
|
||||
|
||||
# GOTCHA #2: INSERT or REPLACE? Both function in a very similar method, with one minor difference. The INSERT command
|
||||
# simply creates a new record/row and places the fields/columns into the table. The REPLACE command will INSERT a new record
|
||||
# into the table, then it compares the Primary Key values of the new record to any pre-existing matches in the table. Any
|
||||
# older records/rows in the table with a matching Primary Key (which is supposed to be unique) will be deleted in favor of
|
||||
# the new record. You might consider using REPLACE even when you want to INSERT just to make sure you don't end up with
|
||||
# duplicate data in your tables.
|
||||
|
||||
print "<B>EXAMPLES USING THE <U>INSERT</U> AND <U>REPLACE</U> SQL COMMANDS.</B><P>"
|
||||
|
||||
# REPLACE
|
||||
try:
|
||||
cursor.execute("REPLACE INTO TEAM (MEMBER_ID,FIRST_NAME,LAST_NAME,REMARK,FAV_COLOR,OPEN_DATE) VALUES ('6','Frederick','Clueless','Clueless Fred','blue',NOW());")
|
||||
except:
|
||||
print "\n\n<PRE>"
|
||||
traceback.print_exc()
|
||||
sys.exit()
|
||||
|
||||
# INSERT -- Note that since the Primary Key for the TEAM table is not specified in our insert command and member_id is an
|
||||
# autoincrement data type, a new member_id is assigned to this inserted record. Try reloading this web page in your browser
|
||||
# a few times to observe the results.
|
||||
try:
|
||||
cursor.execute("INSERT INTO TEAM (FIRST_NAME,LAST_NAME,REMARK,FAV_COLOR,OPEN_DATE) VALUES ('Ruprecht','Lionheart','Lost Rupe','cyan',NOW());")
|
||||
except:
|
||||
print "\n\n<PRE>"
|
||||
traceback.print_exc()
|
||||
sys.exit()
|
||||
|
||||
# INSERT -- This example will cause an INTEGRITY ERROR, because the MEMBER_ID will conflict with an existing MEMBER_ID.
|
||||
try:
|
||||
cursor.execute("INSERT INTO TEAM (MEMBER_ID,FIRST_NAME,LAST_NAME,REMARK,FAV_COLOR,OPEN_DATE) VALUES ('4','Fuzzy','Illogic','Evil Twin of Fuzzy Logic','red',NOW());")
|
||||
except:
|
||||
print "<FONT SIZE=\"1\">SAMPLE INTEGRITY ERROR</FONT><BR>"
|
||||
print "<PRE>"
|
||||
traceback.print_exc()
|
||||
print "</PRE><P>"
|
||||
|
||||
# REQUERY TO SEE RESULTS
|
||||
try:
|
||||
cursor.execute("SELECT * FROM TEAM")
|
||||
except:
|
||||
print "\n\n<PRE>"
|
||||
traceback.print_exc()
|
||||
sys.exit()
|
||||
resultSet = cursor.fetchall()
|
||||
print "<B>ADDING NEW TEAM MEMBERS</B><BR>"
|
||||
print "<FONT SIZE=\"1\">results of query:<BR>"
|
||||
print "<TABLE BORDER=\"1\"><TR>"
|
||||
for cursorFieldname in cursor.description:
|
||||
print "<TD><CENTER><FONT FACE=\"arial\" SIZE=\"2\">" +cursorFieldname[0]+ "</FONT></CENTER></TD>"
|
||||
print "</TR>"
|
||||
for cursorRecord in resultSet:
|
||||
print "<TR>"
|
||||
for cursorField in cursorRecord:
|
||||
print "<TD><FONT FACE=\"arial\" SIZE=\"1\">"
|
||||
print cursorField
|
||||
print "</FONT></TD>"
|
||||
print "</TR>"
|
||||
print "</TABLE>"
|
||||
print "</CENTER>"
|
||||
print " <P></FONT><P><HR><P>"
|
||||
|
||||
# CLOSING THE DATABASE OBJECT
|
||||
try:
|
||||
WebOpsDB.close()
|
||||
except:
|
||||
print "\n\n<PRE>"
|
||||
traceback.print_exc()
|
||||
sys.exit()
|
||||
|
||||
# CONTINUED IN DBTRAINER2
|
||||
# To learn more about replacing and updating records, and performing other SQL functions review
|
||||
# dbtrainer2.
|
||||
|
||||
# END YOUR HTML PAGE
|
||||
print "</FONT></BODY>\n"
|
||||
print "</HTML>\n"
|
124
mysql/examples/dbtrainer2
Normal file
124
mysql/examples/dbtrainer2
Normal file
@ -0,0 +1,124 @@
|
||||
#!/usr/bin/python
|
||||
# TITLE: dbtrainer2
|
||||
# WRITTEN BY: Bradley Stec, July 1999
|
||||
# RuleSpace, Inc.
|
||||
# SUPPORTS: WebOps Database Interface Trainer Script
|
||||
# PURPOSE: This script is a code and output example of how to use the
|
||||
# MySQLdb API to communicate to a database and perform basic
|
||||
# SQL command language requests.
|
||||
# FUNCTION: Both by executing the script and by reading the source code,
|
||||
# a programmer should be able to get a grasp on how the interface
|
||||
# works and may borrow code for their own script projects.
|
||||
# REQUIREMENTS: This script requires the access to the webops module, and that a
|
||||
# database named "test" be installed in the webops specified
|
||||
# database server.
|
||||
#
|
||||
# CHANGES: 7/99 Initial Version
|
||||
|
||||
import sys
|
||||
import webops
|
||||
import traceback
|
||||
sys.stderr = sys.stdout
|
||||
|
||||
# Set Up Page Layout
|
||||
print "content-type: text/html"
|
||||
print
|
||||
print "<HTML>\n"
|
||||
print "<BODY BGCOLOR=\"#FFFFFF\">\n"
|
||||
print "<FONT FACE=\"arial\" SIZE=\"3\"><B>RuleSpace, Inc. WebOps Database Interface Trainer -- Part 2</B><BR><HR>"
|
||||
print "The purpose of this page is to present sample code for interfacing with the databases within the Web Operations server farm. The display below illustrates real database queries as well as how the information is handled and presented.<P>"
|
||||
print "By viewing the CGI script which presents the information below you'll be able to see how the database interface and API works within the WebOps scripting environment.<P>"
|
||||
print "<HR>"
|
||||
|
||||
# Loading The API Support
|
||||
# The API MySQLdb is a thin wrapper around a C program which is also in the site-packages directory called _mysqlmodule.so
|
||||
# The API follows the Python Database API Spec version 2.0 which basically sets standards for what kind of methods will be
|
||||
# used to access databases within the Python environment. The _mysqlmodule.so and MySQLdb.py programs allow a programmer
|
||||
# to pass SQL commands/queries through to a database. The database server may be remote or local. The MySQL database server
|
||||
# software doesn't provide an interactive cursor, so the API programs create a "cursor" in local memory. Read the Python
|
||||
# Database API Spec version 2.0 for details.
|
||||
|
||||
# This command loads the support files
|
||||
import MySQLdb
|
||||
|
||||
# PREPARE TO CONNECT TO DATABASE
|
||||
# This command forms a connection through the support files to the target database server and database name.
|
||||
try:
|
||||
WebOpsDB = MySQLdb.Connection(host=webops.dbserver,user=webops.dbuser,passwd=webops.dbpass,db='test',port=3306,unix_socket="")
|
||||
except:
|
||||
print "\n\n<PRE>"
|
||||
traceback.print_exc()
|
||||
sys.exit()
|
||||
|
||||
# A LITTLE BONUS INFORMATION FROM THE API
|
||||
# The API can provide some information about the connection and server. Note that these functions are
|
||||
# making use of the "db" object which is a sub-class of the WebOpsDB object. The "db" object bypasses the "wrapper"
|
||||
# level of the MySQLdb interface and speaks directly to the C coded _mysqlmodule.so, therefore it is not recommended
|
||||
# that you use this method frequently in timing-sensitive script applications.
|
||||
print "<B>CONNECTED TO</B><BR>"
|
||||
print " server <B> ", WebOpsDB.db.get_host_info(), "</B><BR>"
|
||||
print " running <B>mySQL server v", WebOpsDB.db.get_server_info(), "</B><BR>"
|
||||
print " current status: ",WebOpsDB.db.stat(), "<P>"
|
||||
print "<HR>"
|
||||
|
||||
# CREATE YOUR PERSONAL CONNECTION TO THE "RESULTS" WITHIN THE CONNECTION OBJECT
|
||||
# We haven't actually queried anything yet, so don't get confused, we're just preparing for it.
|
||||
try:
|
||||
cursor = WebOpsDB.cursor()
|
||||
except:
|
||||
print "\n\n<PRE>"
|
||||
traceback.print_exc()
|
||||
sys.exit()
|
||||
|
||||
# EXAMPLE: UPDATING A RECORD
|
||||
# This example modifies an existing field/column with new information using the UPDATE command. It is recommended that
|
||||
# you use this method over a REPLACE command, since REPLACE uses INSERT and requires additional processing for file locking.
|
||||
try:
|
||||
cursor.execute("UPDATE TEAM SET TEAM.FAV_COLOR='green',TEAM.LAST_DATE=NOW() WHERE TEAM.FIRST_NAME='Frederick' AND TEAM.LAST_NAME='Clueless';")
|
||||
except:
|
||||
print "\n\n<PRE>"
|
||||
traceback.print_exc()
|
||||
sys.exit()
|
||||
|
||||
# REQUERY TO SEE RESULTS
|
||||
try:
|
||||
cursor.execute("SELECT * FROM TEAM;")
|
||||
resultSet = cursor.fetchall()
|
||||
except:
|
||||
print "\n\n<PRE>"
|
||||
traceback.print_exc()
|
||||
sys.exit()
|
||||
|
||||
print "<B>EXAMPLES OF USING THE <U>UPDATE</U> SQL COMMAND.</B><P>"
|
||||
print "MODIFYING AN EXISTING RECORD (Fred changes his favorite color!)<BR>"
|
||||
print "<FONT SIZE=\"1\">"
|
||||
print "<TABLE BORDER=\"1\"><TR>"
|
||||
for cursorFieldname in cursor.description:
|
||||
print "<TD><CENTER><FONT FACE=\"arial\" SIZE=\"2\">" +cursorFieldname[0]+ "</FONT></CENTER></TD>"
|
||||
print "</TR>"
|
||||
for cursorRecord in resultSet:
|
||||
print "<TR>"
|
||||
for cursorField in cursorRecord:
|
||||
print "<TD><FONT FACE=\"arial\" SIZE=\"1\">"
|
||||
print cursorField
|
||||
print "</FONT></TD>"
|
||||
print "</TR>"
|
||||
print "</TABLE>"
|
||||
print "</CENTER>"
|
||||
print " <P></FONT><P><HR><P>"
|
||||
|
||||
# CLOSING THE DATABASE OBJECT
|
||||
try:
|
||||
WebOpsDB.close()
|
||||
except:
|
||||
print "\n\n<PRE>"
|
||||
traceback.print_exc()
|
||||
sys.exit()
|
||||
|
||||
# CONTINUED IN DBTRAINER3
|
||||
# To learn more about deleting records, and performing other SQL functions review
|
||||
# dbtrainer3.
|
||||
|
||||
# END YOUR HTML PAGE
|
||||
print "</FONT></BODY>\n"
|
||||
print "</HTML>\n"
|
122
mysql/examples/dbtrainer3
Normal file
122
mysql/examples/dbtrainer3
Normal file
@ -0,0 +1,122 @@
|
||||
#!/usr/bin/python
|
||||
# TITLE: dbtrainer3
|
||||
# WRITTEN BY: Bradley Stec, July 1999
|
||||
# RuleSpace, Inc.
|
||||
# SUPPORTS: WebOps Database Interface Trainer Script
|
||||
# PURPOSE: This script is a code and output example of how to use the
|
||||
# MySQLdb API to communicate to a database and perform basic
|
||||
# SQL command language requests.
|
||||
# FUNCTION: Both by executing the script and by reading the source code,
|
||||
# a programmer should be able to get a grasp on how the interface
|
||||
# works and may borrow code for their own script projects.
|
||||
# REQUIREMENTS: This script requires the access to the webops module, and that a
|
||||
# database named "test" be installed in the webops specified
|
||||
# database server.
|
||||
#
|
||||
# CHANGES: 7/99 Initial Version
|
||||
|
||||
import sys
|
||||
import webops
|
||||
import traceback
|
||||
sys.stderr = sys.stdout
|
||||
|
||||
# Set Up Page Layout
|
||||
print "content-type: text/html"
|
||||
print
|
||||
print "<HTML>\n"
|
||||
print "<BODY BGCOLOR=\"#FFFFFF\">\n"
|
||||
print "<FONT FACE=\"arial\" SIZE=\"3\"><B>RuleSpace, Inc. WebOps Database Interface Trainer -- Part 3</B><BR><HR>"
|
||||
print "The purpose of this page is to present sample code for interfacing with the databases within the Web Operations server farm. The display below illustrates real database queries as well as how the information is handled and presented.<P>"
|
||||
print "By viewing the CGI script which presents the information below you'll be able to see how the database interface and API works within the WebOps scripting environment.<P>"
|
||||
print "<HR>"
|
||||
|
||||
# Loading The API Support
|
||||
# The API MySQLdb is a thin wrapper around a C program which is also in the site-packages directory called _mysqlmodule.so
|
||||
# The API follows the Python Database API Spec version 2.0 which basically sets standards for what kind of methods will be
|
||||
# used to access databases within the Python environment. The _mysqlmodule.so and MySQLdb.py programs allow a programmer
|
||||
# to pass SQL commands/queries through to a database. The database server may be remote or local. The MySQL database server
|
||||
# software doesn't provide an interactive cursor, so the API programs create a "cursor" in local memory. Read the Python
|
||||
# Database API Spec version 2.0 for details.
|
||||
|
||||
# This command loads the support files
|
||||
import MySQLdb
|
||||
|
||||
# PREPARE TO CONNECT TO DATABASE
|
||||
# This command forms a connection through the support files to the target database server and database name.
|
||||
try:
|
||||
WebOpsDB = MySQLdb.Connection(host=webops.dbserver,user=webops.dbuser,passwd=webops.dbpass,db='test',port=3306,unix_socket="")
|
||||
except:
|
||||
print "\n\n<PRE>"
|
||||
traceback.print_exc()
|
||||
sys.exit()
|
||||
|
||||
# A LITTLE BONUS INFORMATION FROM THE API
|
||||
# The API can provide some information about the connection and server. Note that these functions are
|
||||
# making use of the "db" object which is a sub-class of the WebOpsDB object. The "db" object bypasses the "wrapper"
|
||||
# level of the MySQLdb interface and speaks directly to the C coded _mysqlmodule.so, therefore it is not recommended
|
||||
# that you use this method frequently in timing-sensitive script applications.
|
||||
print "<B>CONNECTED TO</B><BR>"
|
||||
print " server <B> ", WebOpsDB.db.get_host_info(), "</B><BR>"
|
||||
print " running <B>mySQL server v", WebOpsDB.db.get_server_info(), "</B><BR>"
|
||||
print " current status: ",WebOpsDB.db.stat(), "<P>"
|
||||
print "<HR>"
|
||||
|
||||
# CREATE YOUR PERSONAL CONNECTION TO THE "RESULTS" WITHIN THE CONNECTION OBJECT
|
||||
# We haven't actually queried anything yet, so don't get confused, we're just preparing for it.
|
||||
try:
|
||||
cursor = WebOpsDB.cursor()
|
||||
except:
|
||||
print "\n\n<PRE>"
|
||||
traceback.print_exc()
|
||||
sys.exit()
|
||||
|
||||
# EXAMPLE: DELETING A RECORD
|
||||
# This example deletes record.
|
||||
try:
|
||||
cursor.execute("DELETE FROM TEAM WHERE FIRST_NAME='Frederick' AND LAST_NAME='Clueless';")
|
||||
cursor.execute("DELETE FROM TEAM WHERE FIRST_NAME='Ruprecht';")
|
||||
except:
|
||||
print "\n\n<PRE>"
|
||||
traceback.print_exc()
|
||||
sys.exit()
|
||||
|
||||
# REQUERY TO SEE RESULTS
|
||||
try:
|
||||
cursor.execute("SELECT * FROM TEAM")
|
||||
resultSet = cursor.fetchall()
|
||||
except:
|
||||
print "\n\n<PRE>"
|
||||
traceback.print_exc()
|
||||
sys.exit()
|
||||
|
||||
print "<B>EXAMPLES OF USING THE <U>DELETE</U> SQL COMMAND.</B><P>"
|
||||
print "DELETING FRED AND HIS FRIEND RUPRECHT<BR>"
|
||||
print "<FONT SIZE=\"1\">"
|
||||
print "<TABLE BORDER=\"1\"><TR>"
|
||||
for cursorFieldname in cursor.description:
|
||||
print "<TD><CENTER><FONT FACE=\"arial\" SIZE=\"2\">" +cursorFieldname[0]+ "</FONT></CENTER></TD>"
|
||||
print "</TR>"
|
||||
for cursorRecord in resultSet:
|
||||
print "<TR>"
|
||||
for cursorField in cursorRecord:
|
||||
print "<TD><FONT FACE=\"arial\" SIZE=\"1\">"
|
||||
print cursorField
|
||||
print "</FONT></TD>"
|
||||
print "</TR>"
|
||||
print "</TABLE>"
|
||||
print "</CENTER>"
|
||||
print " <P></FONT><P><HR><P>"
|
||||
|
||||
# CLOSING THE DATABASE OBJECT
|
||||
try:
|
||||
WebOpsDB.close()
|
||||
except:
|
||||
print "\n\n<PRE>"
|
||||
traceback.print_exc()
|
||||
sys.exit()
|
||||
|
||||
# CONTINUED IN DBTRAINER4
|
||||
# To learn more about converting result sets into Python dictionary data types, see dbtrainer4.
|
||||
|
||||
print "</FONT></BODY>\n"
|
||||
print "</HTML>\n"
|
131
mysql/examples/dbtrainer4
Normal file
131
mysql/examples/dbtrainer4
Normal file
@ -0,0 +1,131 @@
|
||||
#!/usr/bin/python
|
||||
# TITLE: dbtrainer4
|
||||
# WRITTEN BY: Bradley Stec, July 1999
|
||||
# RuleSpace, Inc.
|
||||
# SUPPORTS: WebOps Database Interface Trainer Script
|
||||
# PURPOSE: This script is a code and output example of how to use the
|
||||
# MySQLdb API to communicate to a database and perform basic
|
||||
# SQL command language requests.
|
||||
# FUNCTION: Both by executing the script and by reading the source code,
|
||||
# a programmer should be able to get a grasp on how the interface
|
||||
# works and may borrow code for their own script projects.
|
||||
# REQUIREMENTS: This script requires the access to the webops module, and that a
|
||||
# database named "test" be installed in the webops specified
|
||||
# database server.
|
||||
#
|
||||
# CHANGES: 7/99 Initial Version
|
||||
|
||||
import sys
|
||||
import webops
|
||||
import traceback
|
||||
sys.stderr = sys.stdout
|
||||
|
||||
# Set Up Page Layout
|
||||
print "content-type: text/html"
|
||||
print
|
||||
print "<HTML>\n"
|
||||
print "<BODY BGCOLOR=\"#FFFFFF\">\n"
|
||||
print "<FONT FACE=\"arial\" SIZE=\"3\"><B>RuleSpace, Inc. WebOps Database Interface Trainer -- Part 4</B><BR><HR>"
|
||||
print "The purpose of this page is to present sample code for interfacing with the databases within the Web Operations server farm. The display below illustrates real database queries as well as how the information is handled and presented.<P>"
|
||||
print "By viewing the CGI script which presents the information below you'll be able to see how the database interface and API works within the WebOps scripting environment.<P>"
|
||||
print "<HR>"
|
||||
|
||||
# Loading The API Support
|
||||
# The API MySQLdb is a thin wrapper around a C program which is also in the site-packages directory called _mysqlmodule.so
|
||||
# The API follows the Python Database API Spec version 2.0 which basically sets standards for what kind of methods will be
|
||||
# used to access databases within the Python environment. The _mysqlmodule.so and MySQLdb.py programs allow a programmer
|
||||
# to pass SQL commands/queries through to a database. The database server may be remote or local. The MySQL database server
|
||||
# software doesn't provide an interactive cursor, so the API programs create a "cursor" in local memory. Read the Python
|
||||
# Database API Spec version 2.0 for details.
|
||||
|
||||
# This command loads the support files
|
||||
import MySQLdb
|
||||
|
||||
# PREPARE TO CONNECT TO DATABASE
|
||||
# This command forms a connection through the support files to the target database server and database name.
|
||||
try:
|
||||
WebOpsDB = MySQLdb.Connection(host=webops.dbserver,user=webops.dbuser,passwd=webops.dbpass,db='test',port=3306,unix_socket="")
|
||||
except:
|
||||
print "\n\n<PRE>"
|
||||
traceback.print_exc()
|
||||
sys.exit()
|
||||
|
||||
# A LITTLE BONUS INFORMATION FROM THE API
|
||||
# The API can provide some information about the connection and server. Note that these functions are
|
||||
# making use of the "db" object which is a sub-class of the WebOpsDB object. The "db" object bypasses the "wrapper"
|
||||
# level of the MySQLdb interface and speaks directly to the C coded _mysqlmodule.so, therefore it is not recommended
|
||||
# that you use this method frequently in timing-sensitive script applications.
|
||||
print "<B>CONNECTED TO</B><BR>"
|
||||
print " server <B> ", WebOpsDB.db.get_host_info(), "</B><BR>"
|
||||
print " running <B>mySQL server v", WebOpsDB.db.get_server_info(), "</B><BR>"
|
||||
print " current status: ",WebOpsDB.db.stat(), "<P>"
|
||||
print "<HR>"
|
||||
|
||||
# CREATE YOUR PERSONAL CONNECTION TO THE "RESULTS" WITHIN THE CONNECTION OBJECT
|
||||
# We haven't actually queried anything yet, so don't get confused, we're just preparing for it.
|
||||
try:
|
||||
cursor = WebOpsDB.cursor()
|
||||
except:
|
||||
print "\n\n<PRE>"
|
||||
traceback.print_exc()
|
||||
sys.exit()
|
||||
|
||||
# REQUERY TO SEE RESULTS
|
||||
try:
|
||||
cursor.execute("SELECT * FROM TEAM")
|
||||
resultSet = cursor.fetchall()
|
||||
except:
|
||||
print "\n\n<PRE>"
|
||||
traceback.print_exc()
|
||||
sys.exit()
|
||||
|
||||
# CONVERT THE LIST OF LISTS INTO A DICTIONARY
|
||||
resultDict = {}
|
||||
numColumns = len(cursor.description)-1
|
||||
numRows = len(resultSet)-1
|
||||
cursorColumn = 0
|
||||
cursorRow = 0
|
||||
# Put Field Names In As Keys
|
||||
for cursorFieldname in cursor.description:
|
||||
tempValues = []
|
||||
tempDict = {}
|
||||
tempKey = cursorFieldname[0]
|
||||
while cursorRow <= numRows:
|
||||
# print resultSet[cursorRow][cursorColumn]
|
||||
tempValues.append(str(resultSet[cursorRow][cursorColumn]))
|
||||
cursorRow = cursorRow + 1
|
||||
tempDict = {tempKey:tempValues}
|
||||
cursorRow = 0
|
||||
cursorColumn = cursorColumn + 1
|
||||
resultDict.update(tempDict)
|
||||
print "<P>"
|
||||
|
||||
print "<B>EXAMPLE OF CONVERTING THE CURSOR DATA INTO A PYTHON DICTIONARY.</B><BR>"
|
||||
# NOTE- This column set is different, we're producing the rows by dictionary keys and placing values in the cells.
|
||||
print "<FONT SIZE=\"2\">A different way to slice the data</FONT><P>"
|
||||
print "<FONT SIZE=\"1\">"
|
||||
print "<TABLE BORDER=\"1\">"
|
||||
for cursorFieldname in cursor.description:
|
||||
print "<TR><TD><FONT FACE=\"arial\" SIZE=\"2\">" +cursorFieldname[0]+ "</FONT></TD>"
|
||||
print "<TD><FONT FACE=\"arial\" SIZE=\"2\">"
|
||||
for x in resultDict[cursorFieldname[0]]:
|
||||
print x
|
||||
print ","
|
||||
print "</FONT></TD></TR>"
|
||||
print "</TABLE>"
|
||||
print "</CENTER>"
|
||||
print " <P></FONT><P><HR><P>"
|
||||
|
||||
# CLOSING THE DATABASE OBJECT
|
||||
try:
|
||||
WebOpsDB.close()
|
||||
except:
|
||||
print "\n\n<PRE>"
|
||||
traceback.print_exc()
|
||||
sys.exit()
|
||||
|
||||
# CONTINUED IN DBTRAINER4
|
||||
# To learn more about converting result sets into Python dictionary data types, see dbtrainer4.
|
||||
|
||||
print "</FONT></BODY>\n"
|
||||
print "</HTML>\n"
|
58
mysql/examples/test.sql
Normal file
58
mysql/examples/test.sql
Normal file
@ -0,0 +1,58 @@
|
||||
# MySQL dump 6.0
|
||||
#
|
||||
# Host: localhost Database: test
|
||||
#--------------------------------------------------------
|
||||
# Server version 3.22.24
|
||||
|
||||
#
|
||||
# Table structure for table 'colors'
|
||||
#
|
||||
CREATE TABLE COLORS (
|
||||
COLOR varchar(32) DEFAULT '' NOT NULL,
|
||||
PRIME_COLOR enum('No','Yes') DEFAULT 'No' NOT NULL,
|
||||
LAST_DATE timestamp(14) DEFAULT '' NOT NULL,
|
||||
OPEN_DATE timestamp(14) DEFAULT '' NOT NULL,
|
||||
PRIMARY KEY (COLOR),
|
||||
KEY PRIME_COLOR (PRIME_COLOR),
|
||||
KEY LAST_DATE (LAST_DATE),
|
||||
KEY OPEN_DATE (OPEN_DATE)
|
||||
);
|
||||
|
||||
#
|
||||
# Dumping data for table 'colors'
|
||||
#
|
||||
|
||||
INSERT INTO COLORS VALUES ('red','Yes',NOW(),NOW());
|
||||
INSERT INTO COLORS VALUES ('blue','Yes',NOW(),NOW());
|
||||
INSERT INTO COLORS VALUES ('green','Yes',NOW(),NOW());
|
||||
INSERT INTO COLORS VALUES ('yellow','No',NOW(),NOW());
|
||||
INSERT INTO COLORS VALUES ('orange','No',NOW(),NOW());
|
||||
INSERT INTO COLORS VALUES ('purple','No',NOW(),NOW());
|
||||
INSERT INTO COLORS VALUES ('cyan','No',NOW(),NOW());
|
||||
|
||||
#
|
||||
# Table structure for table 'team'
|
||||
#
|
||||
CREATE TABLE TEAM (
|
||||
MEMBER_ID int(11) DEFAULT '0' NOT NULL auto_increment,
|
||||
FIRST_NAME varchar(32) DEFAULT '' NOT NULL,
|
||||
LAST_NAME varchar(32) DEFAULT '' NOT NULL,
|
||||
REMARK varchar(64) DEFAULT '' NOT NULL,
|
||||
FAV_COLOR varchar(32) DEFAULT '' NOT NULL,
|
||||
LAST_DATE timestamp(14) DEFAULT '' NOT NULL,
|
||||
OPEN_DATE timestamp(14) DEFAULT '' NOT NULL,
|
||||
PRIMARY KEY (MEMBER_ID),
|
||||
KEY FAV_COLOR (FAV_COLOR),
|
||||
KEY LAST_DATE (LAST_DATE),
|
||||
KEY OPEN_DATE (OPEN_DATE)
|
||||
);
|
||||
|
||||
#
|
||||
# Dumping data for table 'team'
|
||||
#
|
||||
|
||||
INSERT INTO TEAM VALUES (1,'Brad','Stec','Techno Needy','aquamarine',NOW(),NOW());
|
||||
INSERT INTO TEAM VALUES (2,'Nick','Borders','Meticulous Nick','blue',NOW(),NOW());
|
||||
INSERT INTO TEAM VALUES (3,'Brittney','McChristy','Data Diva','blue',NOW(),NOW());
|
||||
INSERT INTO TEAM VALUES (4,'Fuzzy','Logic','The Logic Bunny','cyan',NOW(),NOW());
|
||||
|
Reference in New Issue
Block a user