The document discusses writing MySQL scripts using Python's DB-API module. It provides a short 3-sentence summary of the document:
1) Python's DB-API module provides a database application programming interface and the MySQLdb driver allows it to access MySQL databases.
2) An example script is presented that connects to a MySQL database, issues a query to get the server version, and prints the result.
3) The document also discusses using cursors to execute statements and fetch results, handling errors, and retrieving results as tuples or dictionaries.
Www Kitebird Com Articles Pydbapi Html Toc 1AkramWaseem
The document discusses using Python and the DB-API module to write scripts that interact with MySQL databases. It provides an example of a short script that connects to a MySQL database, issues a query to get the server version, and prints the result. It then discusses a more extensive script that handles errors, issues different statement types like INSERT and SELECT, and retrieves result rows using fetchone() and fetchall() methods. The document provides information on installing prerequisites like Python and MySQLdb, and executing the example scripts.
The document discusses using Python's DB-API interface to write scripts that interact with MySQL databases. It describes installing the MySQLdb driver module, creating a connection to a MySQL server, executing queries using cursor objects, and retrieving and printing the results. A sample script is provided that connects to a test database, executes queries to create and populate a table with animal data, then selects and prints the data from the table.
This document summarizes the server.xml file that describes how to start the Tomcat Server. It outlines the main elements in the server.xml file including <Server>, <Service>, <Connector>, <Engine>, <Host>, and <Context>. Each element and its attributes are described, such as the <Connector> element representing the endpoint that receives and responds to client requests, with attributes like port and protocol. An example server.xml file structure is also provided.
The document provides an overview of Tomcat and JBoss, open-source servlet containers. It discusses the origins and frameworks of Tomcat and JBoss, how to get started with Tomcat configuration, deployment, security, and load balancing of Tomcat instances with Apache HTTP Server. Key configuration files for Tomcat are also summarized.
Java Servlet Programming under Ubuntu Linux by Tushar B KuteTushar B Kute
The document provides information on programming simple servlets under Ubuntu GNU/Linux. It discusses what can be built with servlets, the benefits of servlets over CGI, definitions of servlet containers and servlet architecture. It also covers the servlet lifecycle, request and response objects, and the steps to write a simple servlet class, compile it, deploy it on Tomcat, and run it.
This document provides instructions for creating a gRPC Hello World sample in C# using .NET Core. It describes creating client and server projects with protobuf definition files. The server project implements a Greeter service that returns a greeting message. The client project calls the SayHello method to get a response from the server. Running the projects demonstrates a basic gRPC communication.
This summary provides an overview of the Apache installation and configuration document:
1) Apache Tomcat is an open source software that implements the Java Servlet and JavaServer Pages technologies.
2) The document outlines the steps to install Apache on Ubuntu using apt-get.
3) It describes how to configure Apache including directives for access control, authentication, default types, and more.
Www Kitebird Com Articles Pydbapi Html Toc 1AkramWaseem
The document discusses using Python and the DB-API module to write scripts that interact with MySQL databases. It provides an example of a short script that connects to a MySQL database, issues a query to get the server version, and prints the result. It then discusses a more extensive script that handles errors, issues different statement types like INSERT and SELECT, and retrieves result rows using fetchone() and fetchall() methods. The document provides information on installing prerequisites like Python and MySQLdb, and executing the example scripts.
The document discusses using Python's DB-API interface to write scripts that interact with MySQL databases. It describes installing the MySQLdb driver module, creating a connection to a MySQL server, executing queries using cursor objects, and retrieving and printing the results. A sample script is provided that connects to a test database, executes queries to create and populate a table with animal data, then selects and prints the data from the table.
This document summarizes the server.xml file that describes how to start the Tomcat Server. It outlines the main elements in the server.xml file including <Server>, <Service>, <Connector>, <Engine>, <Host>, and <Context>. Each element and its attributes are described, such as the <Connector> element representing the endpoint that receives and responds to client requests, with attributes like port and protocol. An example server.xml file structure is also provided.
The document provides an overview of Tomcat and JBoss, open-source servlet containers. It discusses the origins and frameworks of Tomcat and JBoss, how to get started with Tomcat configuration, deployment, security, and load balancing of Tomcat instances with Apache HTTP Server. Key configuration files for Tomcat are also summarized.
Java Servlet Programming under Ubuntu Linux by Tushar B KuteTushar B Kute
The document provides information on programming simple servlets under Ubuntu GNU/Linux. It discusses what can be built with servlets, the benefits of servlets over CGI, definitions of servlet containers and servlet architecture. It also covers the servlet lifecycle, request and response objects, and the steps to write a simple servlet class, compile it, deploy it on Tomcat, and run it.
This document provides instructions for creating a gRPC Hello World sample in C# using .NET Core. It describes creating client and server projects with protobuf definition files. The server project implements a Greeter service that returns a greeting message. The client project calls the SayHello method to get a response from the server. Running the projects demonstrates a basic gRPC communication.
This summary provides an overview of the Apache installation and configuration document:
1) Apache Tomcat is an open source software that implements the Java Servlet and JavaServer Pages technologies.
2) The document outlines the steps to install Apache on Ubuntu using apt-get.
3) It describes how to configure Apache including directives for access control, authentication, default types, and more.
The document discusses the core concepts of Java web technology including servlet containers, types of servlet containers, the javax.servlet package, the servlet lifecycle, servlet configuration using ServletConfig, sharing data using ServletContext, and request dispatching using RequestDispatcher. A servlet container runs servlets and acts as the interface between the web server and servlets. Servlets are loaded, initialized, service requests, and destroyed according to their lifecycle managed by the servlet container.
Apache is an open source web server software that runs on over half of all internet servers. The document provides instructions on downloading, installing, and configuring Apache on Windows and Linux systems. It also lists and describes 30 different Apache configuration directives that can be used to customize the server setup.
This document discusses approaches to managing architecture in Java and Spring applications. It recommends starting with a strict packages model organized by slices and layers, then using tools like Sonar to analyze dependencies and enforce architecture. It also introduces Hera, a small plugin system that allows selecting plugins based on criteria and callbacks. Hera provides a registry and common access patterns to integrate plugins dynamically.
This document discusses approaches to managing architecture for Java and Spring applications. It covers topics like granularity of modules, layers and slices; using packages and code analysis tools to enforce architecture; a plain Java approach using packages and visibility; and the Hera plugin system for localizing change and enabling flexibility. Hera is a small plugin registry that allows selecting plugins based on criteria and callbacks to extend functionality in a modular way.
Servlets are Java programs that run on a web or application server and act as a middle layer between a request coming from a web browser or other HTTP client and databases or applications on the HTTP server. Servlets receive HTTP requests and return HTTP responses by accepting request parameters, generating dynamic content, accessing databases, and performing network communications using Java. Servlets are commonly used to add dynamic content to web pages and to access backend databases. The lifecycle of a servlet involves initialization, servicing client requests, and destruction. Common servlet APIs include classes for handling HTTP requests and responses, reading request parameters, using cookies and sessions.
2014-10-30 Taverna 3 status
Presented at Taverna Open Development Workshop 2014 in Manchester.
http://dev.mygrid.org.uk/wiki/display/developer/Taverna+Open+Development+Workshop#TavernaOpenDevelopmentWorkshop-Day1-Thursday2014-10-30
This document provides an overview of web application development and servlet technology. It discusses the history and evolution of web pages to dynamic web applications. It then defines web applications and the request-response model. Common Gateway Interface (CGI) is introduced as the first technique for dynamic content, along with its limitations which led to the creation of servlets. Key servlet concepts like the servlet interface, generic servlet, HTTP servlet, and servlet lifecycle methods are covered. The document also examines the HttpServletRequest and HttpServletResponse interfaces and their various methods. Finally, it discusses session tracking approaches including cookies and the session API.
The document summarizes the agenda for a virtual MuleSoft meetup in Thiruvananthapuram, India. The agenda includes introductions, presentations on what's new in Mule 4.3 and custom policy in Mule 4, planning for the next meetup, and networking time. The document provides guidelines for participants and introduces the organizers and speakers. It explains the purpose of the meetup is to learn and share integration experiences among community members.
This document provides instructions for running a sample page view counting application in Kubernetes. It describes:
1. Creating deployments and services to run the application frontend and Redis datastore in Kubernetes. This includes defining a NodePort service to access the application externally.
2. Scaling up the application frontend to run in multiple replicas.
3. Simulating killing frontend pods and accessing the application to show that availability is not impacted despite pods restarting.
4. Providing instructions for editing a live deployment of a real-life application and making it publicly accessible as an example real-world use case.
This document provides an overview of Java servlets, including what servlets are, their advantages over other technologies like CGI scripts, their lifecycle and program structure, deploying servlets on Tomcat, HTTP request methods, accessing request data, and redirecting URLs. Servlets are Java classes that extend functionality to handle HTTP requests and responses. They have advantages like faster performance than CGI scripts and reuse of the Java platform. The servlet lifecycle involves initialization, processing requests, and destruction. Servlets are deployed on a web container like Tomcat by compiling, configuring in web.xml, and placing in the webapps folder.
Servlets are Java classes that extend the functionality of a web server by dynamically generating web pages. Servlets use the Java programming language and are managed by a servlet container that handles loading, unloading, and directing requests. Servlets provide advantages over older technologies like CGI scripts such as better performance, portability, security, and access to full Java features. The basic servlet lifecycle involves initialization, handling requests, and destruction. Servlets can be generic or HTTP-specific, with HTTP servlets providing specialized methods for different HTTP request types. Sessions allow servlets to maintain state across multiple requests.
This document provides guidance on migrating applications from classic ASP to ASP.NET. It discusses key changes between the two frameworks, strategies for migrating code, handling COM and database components, best practices, and compatibility questions. Migrating requires understanding differences in languages, frameworks, and architectures between ASP and ASP.NET and potentially rewriting code to take advantage of new ASP.NET features. A phased, tested approach is recommended.
This document summarizes the key features and changes between versions of Fluentd, an open source data collector.
The main points are:
1) Fluentd v1.0 will provide stable APIs and features while remaining compatible with v0.12 and v0.14. It will have no breaking API changes.
2) New features in v0.14 and v1.0 include nanosecond time resolution, multi-core processing, Windows support, improved buffering and plugins, and more.
3) The goals for v1.0 include migrating more plugins to the new APIs, addressing issues, and improving documentation. A release is planned for Q2 2017.
This document discusses RabbitMQ, an open source message broker implementation of the Advanced Message Queuing Protocol (AMQP). It provides an overview of AMQP and its key mechanisms including message encoding, flow control, queuing, reliability, and security. RabbitMQ is implemented in Erlang and supports client APIs in several languages including Java. The document describes how to install RabbitMQ, connect to it from a Java client, declare exchanges and queues, publish and receive messages, and use request-response patterns. It also covers message properties, acknowledgements, and reliability concepts in RabbitMQ.
Codefresh + BlazeMeter Webinar: Continuous Testing for Containerized Applicat...Brittany Ingram
Slides from Codefresh + BlazeMeter Webinar. Summary & recording posted on our blog- https://codefresh.io/blog/blazemeter-codefresh-webinar-continuous-testing-containerized-applications/
Learn how to containerize your application and set up an automate end-to-end pipeline. Leverage Codefresh to automate your build, test deployments and integrate BlazeMeter into your Continuous Delivery.
This document discusses Java 8 concurrency abstractions including asynchronous result processing using CompletableFuture and optimistic locking using StampedLock. It provides an overview and comparison to previous concurrency APIs. The agenda includes exploring CompletableFuture features like asynchronous execution, chaining reactions, and exception handling. It also covers using StampedLock for optimistic reads, comparing it to the previous ReentrantReadWriteLock approach. Examples are shown for common use cases of these new concurrency APIs.
This document provides an overview of server-side web programming and different technologies used to create dynamic web pages, including Common Gateway Interface (CGI), servlets, and JavaServer Pages (JSP). CGI allows building dynamic web sites by running programs on the server that can generate HTML responses. Servlets provide a Java-based alternative to CGI with improved performance, portability, and security. Servlets use a request-response model and are executed by a servlet container. JSP is a technology that simplifies web page programming by mixing static elements like HTML with scripting code.
This document provides information on servlets including:
- Servlets allow dynamic content and interaction for web applications and can be used to build search engines, e-commerce sites, and more.
- Servlets have better performance than CGI since they remain loaded in memory between requests rather than starting a new process for each request.
- Servlets follow a request-response lifecycle and provide APIs to handle HTTP requests and responses through the Servlet, HttpServletRequest, and HttpServletResponse interfaces.
This document outlines how to create a composer package for managing PHP dependencies. It discusses adding dependencies using composer, creating the package directory structure with src and tests folders, defining a Hello class in the src folder, writing tests for the Hello class in the tests folder, adding autoloading to the composer.json file, pushing the package to Git and releasing it on Packagist, and using the package by requiring it in another project's composer.json file. It also mentions setting up continuous integration for the package.
The document introduces Windows PowerShell, covering its purpose as a command-line tool and scripting language, features and capabilities, command syntax, and use for administration and security. It provides an agenda for a training session that will demonstrate PowerShell basics like using cmdlets and automating tasks, and managing PowerShell security settings.
This document provides instructions for connecting to a MySQL database from Python using the MySQLdb package. It outlines downloading and installing MySQLdb, connecting to the database, creating a cursor to execute queries, and using cursor methods like fetchone() and fetchall() to retrieve data. The steps include uncommenting and editing configuration files during installation, connecting with MySQLdb.connect() and specifying host, user, password, database and port, and executing queries with cursor.execute() and retrieving rows with fetchone() or a list of tuples with fetchall().
This document provides an introduction to Python programming using a hands-on tutorial approach. It discusses obtaining Python for your computer, running a sample Python program called madlib.py to prompt the user for input and print a story, and explains the code for this sample program line-by-line. It emphasizes learning programming concepts and skills through active participation and experimentation rather than just presenting information.
The document discusses the core concepts of Java web technology including servlet containers, types of servlet containers, the javax.servlet package, the servlet lifecycle, servlet configuration using ServletConfig, sharing data using ServletContext, and request dispatching using RequestDispatcher. A servlet container runs servlets and acts as the interface between the web server and servlets. Servlets are loaded, initialized, service requests, and destroyed according to their lifecycle managed by the servlet container.
Apache is an open source web server software that runs on over half of all internet servers. The document provides instructions on downloading, installing, and configuring Apache on Windows and Linux systems. It also lists and describes 30 different Apache configuration directives that can be used to customize the server setup.
This document discusses approaches to managing architecture in Java and Spring applications. It recommends starting with a strict packages model organized by slices and layers, then using tools like Sonar to analyze dependencies and enforce architecture. It also introduces Hera, a small plugin system that allows selecting plugins based on criteria and callbacks. Hera provides a registry and common access patterns to integrate plugins dynamically.
This document discusses approaches to managing architecture for Java and Spring applications. It covers topics like granularity of modules, layers and slices; using packages and code analysis tools to enforce architecture; a plain Java approach using packages and visibility; and the Hera plugin system for localizing change and enabling flexibility. Hera is a small plugin registry that allows selecting plugins based on criteria and callbacks to extend functionality in a modular way.
Servlets are Java programs that run on a web or application server and act as a middle layer between a request coming from a web browser or other HTTP client and databases or applications on the HTTP server. Servlets receive HTTP requests and return HTTP responses by accepting request parameters, generating dynamic content, accessing databases, and performing network communications using Java. Servlets are commonly used to add dynamic content to web pages and to access backend databases. The lifecycle of a servlet involves initialization, servicing client requests, and destruction. Common servlet APIs include classes for handling HTTP requests and responses, reading request parameters, using cookies and sessions.
2014-10-30 Taverna 3 status
Presented at Taverna Open Development Workshop 2014 in Manchester.
http://dev.mygrid.org.uk/wiki/display/developer/Taverna+Open+Development+Workshop#TavernaOpenDevelopmentWorkshop-Day1-Thursday2014-10-30
This document provides an overview of web application development and servlet technology. It discusses the history and evolution of web pages to dynamic web applications. It then defines web applications and the request-response model. Common Gateway Interface (CGI) is introduced as the first technique for dynamic content, along with its limitations which led to the creation of servlets. Key servlet concepts like the servlet interface, generic servlet, HTTP servlet, and servlet lifecycle methods are covered. The document also examines the HttpServletRequest and HttpServletResponse interfaces and their various methods. Finally, it discusses session tracking approaches including cookies and the session API.
The document summarizes the agenda for a virtual MuleSoft meetup in Thiruvananthapuram, India. The agenda includes introductions, presentations on what's new in Mule 4.3 and custom policy in Mule 4, planning for the next meetup, and networking time. The document provides guidelines for participants and introduces the organizers and speakers. It explains the purpose of the meetup is to learn and share integration experiences among community members.
This document provides instructions for running a sample page view counting application in Kubernetes. It describes:
1. Creating deployments and services to run the application frontend and Redis datastore in Kubernetes. This includes defining a NodePort service to access the application externally.
2. Scaling up the application frontend to run in multiple replicas.
3. Simulating killing frontend pods and accessing the application to show that availability is not impacted despite pods restarting.
4. Providing instructions for editing a live deployment of a real-life application and making it publicly accessible as an example real-world use case.
This document provides an overview of Java servlets, including what servlets are, their advantages over other technologies like CGI scripts, their lifecycle and program structure, deploying servlets on Tomcat, HTTP request methods, accessing request data, and redirecting URLs. Servlets are Java classes that extend functionality to handle HTTP requests and responses. They have advantages like faster performance than CGI scripts and reuse of the Java platform. The servlet lifecycle involves initialization, processing requests, and destruction. Servlets are deployed on a web container like Tomcat by compiling, configuring in web.xml, and placing in the webapps folder.
Servlets are Java classes that extend the functionality of a web server by dynamically generating web pages. Servlets use the Java programming language and are managed by a servlet container that handles loading, unloading, and directing requests. Servlets provide advantages over older technologies like CGI scripts such as better performance, portability, security, and access to full Java features. The basic servlet lifecycle involves initialization, handling requests, and destruction. Servlets can be generic or HTTP-specific, with HTTP servlets providing specialized methods for different HTTP request types. Sessions allow servlets to maintain state across multiple requests.
This document provides guidance on migrating applications from classic ASP to ASP.NET. It discusses key changes between the two frameworks, strategies for migrating code, handling COM and database components, best practices, and compatibility questions. Migrating requires understanding differences in languages, frameworks, and architectures between ASP and ASP.NET and potentially rewriting code to take advantage of new ASP.NET features. A phased, tested approach is recommended.
This document summarizes the key features and changes between versions of Fluentd, an open source data collector.
The main points are:
1) Fluentd v1.0 will provide stable APIs and features while remaining compatible with v0.12 and v0.14. It will have no breaking API changes.
2) New features in v0.14 and v1.0 include nanosecond time resolution, multi-core processing, Windows support, improved buffering and plugins, and more.
3) The goals for v1.0 include migrating more plugins to the new APIs, addressing issues, and improving documentation. A release is planned for Q2 2017.
This document discusses RabbitMQ, an open source message broker implementation of the Advanced Message Queuing Protocol (AMQP). It provides an overview of AMQP and its key mechanisms including message encoding, flow control, queuing, reliability, and security. RabbitMQ is implemented in Erlang and supports client APIs in several languages including Java. The document describes how to install RabbitMQ, connect to it from a Java client, declare exchanges and queues, publish and receive messages, and use request-response patterns. It also covers message properties, acknowledgements, and reliability concepts in RabbitMQ.
Codefresh + BlazeMeter Webinar: Continuous Testing for Containerized Applicat...Brittany Ingram
Slides from Codefresh + BlazeMeter Webinar. Summary & recording posted on our blog- https://codefresh.io/blog/blazemeter-codefresh-webinar-continuous-testing-containerized-applications/
Learn how to containerize your application and set up an automate end-to-end pipeline. Leverage Codefresh to automate your build, test deployments and integrate BlazeMeter into your Continuous Delivery.
This document discusses Java 8 concurrency abstractions including asynchronous result processing using CompletableFuture and optimistic locking using StampedLock. It provides an overview and comparison to previous concurrency APIs. The agenda includes exploring CompletableFuture features like asynchronous execution, chaining reactions, and exception handling. It also covers using StampedLock for optimistic reads, comparing it to the previous ReentrantReadWriteLock approach. Examples are shown for common use cases of these new concurrency APIs.
This document provides an overview of server-side web programming and different technologies used to create dynamic web pages, including Common Gateway Interface (CGI), servlets, and JavaServer Pages (JSP). CGI allows building dynamic web sites by running programs on the server that can generate HTML responses. Servlets provide a Java-based alternative to CGI with improved performance, portability, and security. Servlets use a request-response model and are executed by a servlet container. JSP is a technology that simplifies web page programming by mixing static elements like HTML with scripting code.
This document provides information on servlets including:
- Servlets allow dynamic content and interaction for web applications and can be used to build search engines, e-commerce sites, and more.
- Servlets have better performance than CGI since they remain loaded in memory between requests rather than starting a new process for each request.
- Servlets follow a request-response lifecycle and provide APIs to handle HTTP requests and responses through the Servlet, HttpServletRequest, and HttpServletResponse interfaces.
This document outlines how to create a composer package for managing PHP dependencies. It discusses adding dependencies using composer, creating the package directory structure with src and tests folders, defining a Hello class in the src folder, writing tests for the Hello class in the tests folder, adding autoloading to the composer.json file, pushing the package to Git and releasing it on Packagist, and using the package by requiring it in another project's composer.json file. It also mentions setting up continuous integration for the package.
The document introduces Windows PowerShell, covering its purpose as a command-line tool and scripting language, features and capabilities, command syntax, and use for administration and security. It provides an agenda for a training session that will demonstrate PowerShell basics like using cmdlets and automating tasks, and managing PowerShell security settings.
This document provides instructions for connecting to a MySQL database from Python using the MySQLdb package. It outlines downloading and installing MySQLdb, connecting to the database, creating a cursor to execute queries, and using cursor methods like fetchone() and fetchall() to retrieve data. The steps include uncommenting and editing configuration files during installation, connecting with MySQLdb.connect() and specifying host, user, password, database and port, and executing queries with cursor.execute() and retrieving rows with fetchone() or a list of tuples with fetchall().
This document provides an introduction to Python programming using a hands-on tutorial approach. It discusses obtaining Python for your computer, running a sample Python program called madlib.py to prompt the user for input and print a story, and explains the code for this sample program line-by-line. It emphasizes learning programming concepts and skills through active participation and experimentation rather than just presenting information.
The document provides a reference guide for HTML5 tags including the tag name, which HTML versions the tag is valid for, and common attributes for each tag. It lists over 100 tags across 4 pages, providing brief descriptions and allowed attributes for each. Key tags covered include common text tags like <p>, <strong>, and <em>, media tags like <audio> and <video>, form tags like <button> and <input>, semantic sectioning tags like <header> and <footer>, and lists tags like <ul> and <ol>.
The document provides an overview of the Python programming language. It discusses that Python is an interpreted, interactive, object-oriented language created by Guido van Rossum in the late 1980s. It describes Python as high-level, portable, and has an extensive standard library. The document then covers Python variables and data types, basic operators, and provides examples of Python code, including defining variables, strings, lists, tuples, and dictionaries.
The document outlines a Python training course that will cover topics such as the Python shell, data types, built-in functions, operators, flow control, syntax, data structures, file input/output, regular expressions, and Python library modules. Exercises will be done after each topic is taught to allow students to practice writing Python scripts.
The document discusses advanced features of the AjaxTags Library including autocomplete textboxes that populate associated values in other textboxes. It provides an example of an autocomplete textbox that populates a secondary textbox with a linked Spanish word when an English animal is selected. The server-side code returns an XML list with names and values to map selections to the secondary field. Training courses are also advertised on Ajax, Java EE and other technologies.
This document provides an introduction to the Python programming language. It discusses Python's easy-to-learn and powerful features such as its efficient data structures and object-oriented approach. The document also covers Python's syntax, dynamic typing, scripting capabilities, extensive standard library, and ability to be extended via C/C++. It is intended to introduce readers to Python's basic concepts and features in an informal manner.
This article introduces LAMP software stack on zLinux (Linux on IBM System z). Let’s call it zLAMP. We will delve into configuring and starting up individual components of zLAMP and then downloading, installing and testing few LAMP based off the shelf open source applications
Interface python with sql database10.pdfHiteshNandi
This document provides information about interfacing Python with SQL databases. It discusses using Python's Database API to connect to databases like MySQL and perform SQL queries. Specific topics covered include establishing a connection, creating a cursor object to execute queries, creating/modifying tables, and inserting/searching/fetching records from tables at runtime. The document aims to demonstrate how to interface a Python program with a backend SQL database.
The document discusses interfacing Python with SQL databases. It begins by explaining what a database is and why it is important to develop projects/software that can interface with databases using a programming language like Python. It then provides examples of connecting to an SQL database from Python using MySQL connectors and MySQLdb. It demonstrates how to create, read, update and delete data from database tables using SQL queries executed from Python scripts.
This document provides instructions for connecting to a MySQL database from a C++ application using MySQL Connector/C++. It discusses installing the MySQL Connector/C++ driver, making a connection to a MySQL database, executing queries to retrieve and insert data, and closing the connection. Sample C++ code is provided to demonstrate connecting to a database, running queries, processing result sets, and disconnecting.
The mysqlnd replication and load balancing pluginUlf Wendel
The mysqlnd replication and load balancing plugin for mysqlnd makes using MySQL Replication from PHP much easier. The plugin takes care of Read/Write splitting, Load Balancing, Failover and Connection Pooling. Lazy Connections, a feature not only useful with replication, help reducing the MySQL server load. Like any other mysqlnd plugin, the plugin operates mostly transparent from an applications point of view and can be used in a drop-in style.
This document provides information on serverless computing platforms from Azure, AWS, and Google. It outlines the supported programming languages and runtimes for each platform's functions as well as common event sources that can trigger function execution, such as S3 buckets, queues, and HTTP requests. It also lists serverless database options and notes that serverless computing allows for automatic scaling of resources and reduced management overhead compared to traditional reserved servers.
Bare Metal to OpenStack with Razor and ChefMatt Ray
Razor is an open source provisioning tool that was originally developed by EMC and Puppet Labs. It can discover hardware, select images to deploy, and provision nodes using model-based provisioning. The demo showed setting up a Razor appliance, adding images, models, policies, and brokers. It then deployed an OpenStack all-in-one environment to a new VM using Razor and Chef. The OpenStack cookbook walkthrough explained the roles, environments, and cookbooks used to deploy and configure OpenStack components using Chef.
The document provides an overview of MySQL, including that it is a fast, multi-threaded SQL database server written in C/C++ that works across many operating systems. It discusses installing and using MySQL, creating and populating databases and tables, and performing queries.
The document provides an overview of MySQL, including:
- MySQL is a fast, multi-threaded, multi-user SQL database server.
- It is open source and dual licensed, and supports many operating systems.
- The document discusses installing and connecting to MySQL, and provides examples of basic queries.
This document provides instructions for deploying a simple LAMP stack application using Cloud Application Manager. It defines the database and app tiers separately, connecting them with a binding. The database tier is an Amazon RDS MySQL instance. The app tier installs Apache, PHP and connects to the database using the binding. It takes under 30 minutes to complete the deployment.
ASP is an active server page technology developed by Microsoft that allows web developers to build dynamic websites and web applications. ASP files can contain HTML tags, text, and scripting code. Scripts in ASP files are executed on the server rather than in the user's web browser. Common uses of ASP include dynamically generating and customizing web page content, accessing databases to display information to users, and providing more security since ASP code is not visible to users.
This document discusses Python database programming. It introduces databases and how they store data in tables connected through columns. It discusses SQL for creating, accessing, and manipulating database data. It then discusses how Python supports various databases and database operations. It covers the Python DB-API for providing a standard interface for database programming. It provides examples of connecting to a database, executing queries, and retrieving and inserting data.
Slowly the power of mysqlnd plugins become visible. Mysqlnd plugins challenge MySQL Proxy and are often a noteworthy, if not superior, alternative alternative to MySQL Proxy for PHP users. Plugins can do almost anything that MySQL Proxy can do - but on the client. Please find details in the slides. The presentation has been given today at the PHP track on FrOSCon.
This document discusses microservices using Node.js and JavaScript. It covers building an HTTP microservice with Express including routing, structure, database integration, logging and testing. It also discusses building command-based microservices with Seneca including patterns, plugins, and queueing. Finally, it discusses containerization with Docker, API gateways, testing, process management with PM2, and some considerations around when microservices may not be the best solution.
HTTP, JSON, JavaScript, Map&Reduce built-in to MySQLUlf Wendel
HTTP, JSON, JavaScript, Map&Reduce built in to MySQL - make it happen, today. See how a MySQL Server plugin be developed to built all this into MySQL. A new direct wire between MySQL and client-side JavaScript is created. MySQL speaks HTTP, replies JSON and offers server-side JavaScript. Server-side JavaScript gets access to MySQL data and does Map&Reduce of JSON documents stored in MySQL. Fast? 2-4x faster than proxing client-side JavaScript request through PHP/Apache. Reasonable results...
This document provides an overview of AWS Lambda and how it enables serverless application development. It discusses how AWS Lambda allows developers to run code without provisioning or managing servers, and how it can automatically scale in response to triggers from various AWS services. It also summarizes some key capabilities like bringing custom code, parallel execution, integration with other AWS services, and event-driven or pull-based invocation models.
This document provides information about an internship at Amazon Inc. for Asmita Sharma from 2012-2015. It includes details about her role as a Software Development Engineer Intern on the Balance Tracking System team, the development environment and tools used, and an overview of operational and minor project tasks completed during the internship related to migrating packages between Java versions and removing reconciliation functionality from pipelines. A major project goal to support query APIs on S3 is also outlined.
Mseduebookexcitinglearningweb Final 120914022330 Phpapp02AkramWaseem
This chapter discusses why technology should be used in schools. It notes that technology has revolutionized many areas of life but that education has yet to see a truly transformative impact. The chapter aims to enhance understanding of the benefits of technology across the curriculum and provide practical information on how it can increase student motivation and learning.
This document provides a tutorial on using the Simple Object Access Protocol (SOAP) for communication between components using XML messaging. It uses an example of an HTML calendar widget that can receive event updates and display event listings for a given month. The tutorial demonstrates making a SOAP request to add an event listing and get the event listings for a month using the IDL-defined interface for the calendar component.
This document provides an introduction to converting HTML documents to XHTML, including the basic syntax changes needed like making all tags lowercase and closing all tags. It provides examples of correct XHTML markup for different tags. It also explains the new DOCTYPE declaration and shows a sample well-formed XHTML document with the discussed syntax. Resources for learning more about XHTML are listed at the end.
The document provides an overview of the Unified Modeling Language (UML). UML was created by the Object Management Group as a standard modeling language for visualizing, specifying, constructing, and documenting software systems. It introduces key concepts of UML including its goals, building blocks, basic notations, and types of modeling. UML uses standard visual notations like diagrams, classes, use cases to model both structural and behavioral aspects of a system.
This document provides an introduction to converting HTML documents to XHTML, including the basic syntax changes needed like making all tags lowercase and closing all tags. It provides examples of correct XHTML markup for different tags. It also explains the new DOCTYPE declaration and shows a sample well-formed XHTML document incorporating all the discussed changes. Resources for learning more about XHTML are listed at the end.
This document is a complete list of ASCII codes from 0 to 255. It includes the ASCII code number, symbol, and description for each code. Common symbols include letters, numbers, punctuation marks, and some international characters with diacritics. Control codes at the beginning are also included, such as NULL, SOH, STX, ETX.
Random And Dynamic Images Using Python CgiAkramWaseem
This document discusses using Python to generate random and dynamic images through CGI scripts. It begins with an overview and introduction to Python CGI programming and the Python Imaging Library (PIL). It then demonstrates a simple Python CGI script that serves a static image file. Next, it shows a random image script that selects a random image file from a directory. The document also covers using PIL to dynamically generate images and build a script that generates a random gradient image. It concludes by discussing building more advanced dynamic image scripts that accept arguments and graph log files.
This document provides instructions for setting up MySQL for Python (MySQLdb) on Mac OS X. It describes downloading MySQL from mysql.com and installing it, then downloading and building MySQLdb from sourceforge.net. It notes potential issues like missing header files and explains how to fix them by installing additional developer packages or changing symbolic links. Comments provide corrections and additional troubleshooting tips for issues users encountered.
Internet Programming With Python PresentationAkramWaseem
This document provides an overview and agenda for the "Internet Programming with Python" tutorial being given at OSCON 2009. The tutorial will cover network programming with sockets in Python, including an introduction to client-server architecture and networking concepts. It will also cover internet client programming, CGI programming, and conclude with a question and answer session. The target audience is software engineers and system administrators with a basic Python knowledge seeking an introduction to internet programming topics in Python.
This document provides information about Common Gateway Interface (CGI) programming and how web browsers communicate with web servers. It discusses how browsers make requests to servers, how servers respond, and how form data is transmitted from browsers to CGI programs using GET and POST methods. It also covers cookies, file uploads, and provides examples of simple CGI programs in Perl and Python.
This document discusses how to use Python for web development. It presents several methods for integrating Python with a web server, including the Common Gateway Interface (CGI) which allows Python programs to communicate with the server. CGI is the oldest interface but has performance limitations. Newer interfaces like WSGI allow Python programs to emulate CGI while avoiding its downsides. The document provides a simple CGI script example for testing integration and discusses common issues with CGI scripts. It also introduces several popular Python web frameworks.
This document is a tutorial for learning to program. It covers many programming concepts and techniques over 27 chapters. It provides an introduction to programming, the basics of programming structures and syntax, working with data, conditionals, functions, file handling, classes and object oriented programming, GUI programming, and more advanced topics. The tutorial is available online and was also published as a book, which is now available through print-on-demand. Translations of the tutorial exist in several other languages as well. The author provides updates on changes and additions to the content.
1. Writing MySQL Scripts with Python DB-API
Paul DuBois
paul@kitebird.com
Document revision: 1.02
Last update: 2006-09-17
Python is one of the more popular Open Source programming languages, owing largely to its own native
expressiveness as well as to the variety of support modules that are available to extend its capabilities. One
of these modules is DB-API, which, as the name implies, provides a database application programming
interface. DB-API is designed to be relatively independent of details specific to any given database engine,
to help you write database-access scripts that are portable between engines.
DB-API’s design is similar to that used by Perl and Ruby DBI modules, the PHP PEAR DB class, and the
Java JDBC interface: It uses a two-level architecture in which the top level provides an abstract interface
that is similar for all supported database engines, and a lower level consisting of drivers for specific engines
that handle engine-dependent details. This means, of course, that to use DB-API for writing Python scripts,
you must have a driver for your particular database system. For MySQL, DB-API provides database access
by means of the MySQLdb driver. This document begins by discussing driver installation (in case you
don’t have MySQLdb), then moves on to cover how to write DB-API scripts.
MySQLdb Installation
To write MySQL scripts that use DB-API, Python itself must be installed. That will almost certainly be
true if you’re using Unix, but is less likely for Windows. Installers for either platform can be found on the
Python web site (see the ‘‘Resources’’ section at the end of this document).
Verify that your version of Python is 2.3.4 or later, and that the MySQLdb module is installed. You can
check both of these requirements by running Python in interactive mode from the command line prompt
(something like % for Unix or C:> for Windows):
% python
Python 2.4.3 (#1, Aug 29 2006, 14:45:33)
[GCC 3.4.6 (Gentoo 3.4.6-r1, ssp-3.4.5-1.0, pie-8.7.9)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import MySQLdb
Assuming that you have a recent enough version of Python and that no error occurs when you issue the
import MySQLdb statement, you’re ready to begin writing database-access scripts and you can skip to
the next section. However, if you get the following error, you need to obtain and install MySQLdb first:
>>> import MySQLdb
Traceback (most recent call last):
File "<stdin>", line 1, in ?
ImportError: No module named MySQLdb
To obtain MySQLdb, visit the ‘‘Resources’’ section to see where to fetch a distribution appropriate for your
system. Precompiled binaries may available for your platform, or you can install from source. If you use a
binary distribution, install it using your platform’s usual package installation procedure. To build and
install from source, move into the top-level directory of the MySQLdb distribution and issue the following
commands. (Under Unix, it’s likely that you’ll need to run the second command as root so that the driver
files can be copied into your Python installation.)
Revision date: 2006-09-17 Printed: 2006-09-17
2. Writing MySQL Scripts with Python DB-API 2-
% python setup.py build
% python setup.py install
If you encounter problems, check the README file included with the MySQLdb distribution.
A Short DB-API Script
Scripts that access MySQL through DB-API using MySQLdb generally perform the following steps:
1. Import the MySQLdb module
2. Open a connection to the MySQL server
3. Issue statements and retrieve their results
4. Close the server connection
The rest of this section presents a short DB-API script that illustrates the basic elements of these steps.
Later sections discuss specific aspects of script-writing in more detail.
Writing the Script
Use a text editor to create a file named server_version.py that contains the following script. This script uses
MySQLdb to interact with the MySQL server, albeit in relatively rudimentary fashion—all it does is ask the
server for its version string:
# server_version.py - retrieve and display database server version
import MySQLdb
conn = MySQLdb.connect (host = "localhost",
user = "testuser",
passwd = "testpass",
db = "test")
cursor = conn.cursor ()
cursor.execute ("SELECT VERSION()")
row = cursor.fetchone ()
print "server version:", row[0]
cursor.close ()
conn.close ()
The import statement tells Python that the script needs to use the code in the MySQLdb module. This
statement must precede any attempt to connect to the MySQL server. Then the connection is established by
invoking the connect() method of the MySQLdb driver with the proper connection parameters. These
include the hostname where the server is running, the username and password for your MySQL account,
and the name of the database that you want to use. connect() argument list syntax varies among driv-
ers; for MySQLdb, the arguments are allowed to be given in name = value format, which has the advan-
tage that you can specify them in any order. server_version.py makes a connection to the MySQL server on
the local host to access the test database with a username and password of testuser and testpass:
conn = MySQLdb.connect (host = "localhost",
user = "testuser",
passwd = "testpass",
db = "test")
If the connect() call succeeds, it returns a connection object that serves as the basis for further interac-
tion with MySQL. If the call fails, it raises an exception. (server_version.py doesn’t handle the exception,
so an error at this point terminates the script. Error handling is covered later in this document.)
Revision date: 2006-09-17 Printed: 2006-09-17
3. -3- Writing MySQL Scripts with Python DB-API
After the connection object has been obtained, server_version.py invokes its cursor() method to create a
cursor object for processing statements. The script uses this cursor to issue a SELECT VERSION() state-
ment, which returns a string containing server version information:
cursor = conn.cursor ()
cursor.execute ("SELECT VERSION()")
row = cursor.fetchone ()
print "server version:", row[0]
cursor.close ()
The cursor object’s execute() method sends the statement to the server and fetchone() retrieves a
row as a tuple. For the statement shown here, the tuple contains a single value, which the script prints. (If
no row is available, fetchone() actually will return the value None; server_version.py blithely assumes
that this won’t happen, an assumption that you normally should not make. In later examples, we’ll handle
this case.) Cursor objects can be used to issue multiple statements, but server_version.py has no more need
for cursor after getting the version string, so it closes it.
Finally, the script invokes the connection object’s close() method to disconnect from the server:
conn.close ()
After that, conn becomes invalid and should not be used to access the server.
Running the Script
To execute the server_version.py script, invoke Python from the command line prompt and tell it the script
name. You should see a result something like this:
% python server_version.py
server version: 5.1.12-beta-log
This indicates that the MySQL server version is 5.1.12; the -beta and -log suffixes tell us the distribu-
tion stability level and that query logging is enabled. (You might see other suffixes than those shown here.
For example, if you have debugging enabled, you’ll see a -debug suffix.)
It’s possible to set up the script so that it can be run by name without invoking Python explicitly. Under
Unix, add an initial #! line to the script that specifies the full pathname of the Python interpreter. This tells
the system what program should execute the script. For example, if Python lives at /usr/bin/python on your
system, add the following as the first line of the script:
#!/usr/bin/python
Then use chmod to make the script executable, and you’ll be able to run it directly:
% chmod +x server_version.py
% ./server_version.py
(The leading ‘‘./’’ tells your command interpreter explicitly that the script is located in your current direc-
tory. Many Unix accounts are set up not to search the current directory when looking for commands.)
Under Windows, the #! line is unnecessary (although it’s harmless, so you need not remove it if you write
the script on a Unix system and then move it to a Windows box). Instead, you can set up a filename associ-
ation so that .py scripts will be associated with Python. Instead of using chmod to make the script
executable, open the Folder Options item in the Control Panel and select its File Types tab. File Types
enables you to set up an association for files that end with .py to tell Windows to execute them with Python.
Then you can invoke the script by name:
C:> server_version.py
If you install ActiveState Python on Windows, the ActiveState installer sets up the association automati-
cally as part of the installation process.
Revision date: 2006-09-17 Printed: 2006-09-17
4. Writing MySQL Scripts with Python DB-API 4-
A More Extensive DB-API Script
server_version.py has a number of shortcomings. For example, it doesn’t catch exceptions or indicate what
went wrong if an error occurs, and it doesn’t allow for the possibility that the statement it runs might not
return any results. This section shows how to address these issues using a more elaborate script, animal.py,
that uses a table containing animal names and categories:
CREATE TABLE animal
(
name CHAR(40),
category CHAR(40)
)
If you’ve read the PEAR DB document available at the Kitebird site (see ‘‘Resources’’), you might recog-
nize this table and some of the statements issued by animal.py; they were used in that document, too.
The animal.py script begins like this (including the #! line, should you intend to run the script on a Unix
system):
#!/usr/bin/python
# animal.py - create animal table and
# retrieve information from it
import sys
import MySQLdb
As with server_version.py, the script imports MySQLdb, but it also imports the sys module for use in
error handling. (animal.py uses sys.exit() to return 1 to indicate abnormal termination if an error
occurs.)
Error Handling
After importing the requisite modules, animal.py establishes a connection to the server using the con-
nect() call. To allow for the possibility of connection failure (for example, so that you can display the
reason for the failure), it’s necessary to catch exceptions. To handle exceptions in Python, put your code in
a try statement and include an except clause that contains the error-handling code. The resulting con-
nection sequence looks like this:
try:
conn = MySQLdb.connect (host = "localhost",
user = "testuser",
passwd = "testpass",
db = "test")
except MySQLdb.Error, e:
print "Error %d: %s" % (e.args[0], e.args[1])
sys.exit (1)
The except clause names an exception class (MySQLdb.Error in this example) to obtain the database-
specific error information that MySQLdb can provide, as well as a variable (e) in which to store the infor-
mation. If an exception occurs, MySQLdb makes this information available in e.args, a two-element
tuple containing the numeric error code and a string describing the error. The except clause shown in the
example prints both values and exits.
Any database-related statements can be placed in a similar try/except structure to trap and report
errors; for brevity, the following discussion doesn’t show the exception-handling code. (The complete text
of animal.py is listed in the Appendix.)
Revision date: 2006-09-17 Printed: 2006-09-17
5. -5- Writing MySQL Scripts with Python DB-API
Methods for Issuing Statements
The next section of animal.py creates a cursor object and uses it to issue statements that set up and populate
the animal table:
cursor = conn.cursor ()
cursor.execute ("DROP TABLE IF EXISTS animal")
cursor.execute ("""
CREATE TABLE animal
(
name CHAR(40),
category CHAR(40)
)
""")
cursor.execute ("""
INSERT INTO animal (name, category)
VALUES
(’snake’, ’reptile’),
(’frog’, ’amphibian’),
(’tuna’, ’fish’),
(’racoon’, ’mammal’)
""")
print "Number of rows inserted: %d" % cursor.rowcount
Note that this code includes no error checking. (Remember that it will be placed in a try statement; errors
will trigger exceptions that are caught and handled in the corresponding except clause, which allows the
main flow of the code to read more smoothly.) The statements perform the following actions:
1. Drop the animal table if it already exists, to begin with a clean slate.
2. Create the animal table.
3. Insert some data into the table and report the number of rows added.
Each statement is issued by invoking the cursor object’s execute() method. The first two statements
produce no result, but the third produces a count indicating the number of rows inserted. The count is
available in the cursor’s rowcount attribute. (Some database interfaces provide this count as the return
value of the statement-execution call, but that is not true for DB-API.)
The animal table is set up at this point, so we can issue SELECT statements to retrieve information from
it. As with the preceding statements, SELECT statements are issued using execute(). However, unlike
statements such as DROP or INSERT, SELECT statements generate a result set that you must retrieve.
That is, execute() only issues the statement, it does not return the result set. You can use
fetchone() to get the rows one at a time, or fetchall() to get them all at once. animal.py uses both
approaches. Here’s how to use fetchone() for row-at-a-time retrieval:
cursor.execute ("SELECT name, category FROM animal")
while (1):
row = cursor.fetchone ()
if row == None:
break
print "%s, %s" % (row[0], row[1])
print "Number of rows returned: %d" % cursor.rowcount
fetchone() returns the next row of the result set as a tuple, or the value None if no more rows are avail-
able. The loop checks for this and exits when the result set has been exhausted. For each row returned, the
tuple contains two values (that’s how many columns the SELECT statement asked for), which animal.py
prints. The print statement shown above accesses the individual tuple elements. However, because they
are used in order of occurrence within the tuple, the print statement could just as well have been written
like this:
Revision date: 2006-09-17 Printed: 2006-09-17
6. Writing MySQL Scripts with Python DB-API 6-
print "%s, %s" % row
After displaying the statement result, the script also prints the number of rows returned (available as the
value of the rowcount attribute).
fetchall() returns the entire result set all at once as a tuple of tuples, or as an empty tuple if the result
set is empty. To access the individual row tuples, iterate through the row set that fetchall() returns:
cursor.execute ("SELECT name, category FROM animal")
rows = cursor.fetchall ()
for row in rows:
print "%s, %s" % (row[0], row[1])
print "Number of rows returned: %d" % cursor.rowcount
This code prints the row count by accessing rowcount, just as for the fetchone() loop. Another way
to determine the row count when you use fetchall() is by taking the length of the value that it returns:
print "%d rows were returned" % len (rows)
The fetch loops shown thus far retrieve rows as tuples. It’s also possible to fetch rows as dictionaries,
which enables you to access column values by name. The following code shows how to do this. Note that
dictionary access requires a different kind of cursor, so the example closes the cursor and obtains a new one
that uses a different cursor class:
cursor.close ()
cursor = conn.cursor (MySQLdb.cursors.DictCursor)
cursor.execute ("SELECT name, category FROM animal")
result_set = cursor.fetchall ()
for row in result_set:
print "%s, %s" % (row["name"], row["category"])
print "Number of rows returned: %d" % cursor.rowcount
NULL values in a result set are returned as None to your program.
MySQLdb supports a placeholder capability that enables you to bind data values to special markers within
the statement string. This provides an alternative to embedding the values directly into the statement. The
placeholder mechanism handles adding quotes around data values, and it escapes any special characters that
occur within values. The following examples demonstrate an UPDATE statement that changes snake to
turtle, first using literal values and then using placeholders. The literal-value statement looks like this:
cursor.execute ("""
UPDATE animal SET name = ’turtle’
WHERE name = ’snake’
""")
print "Number of rows updated: %d" % cursor.rowcount
Alternatively, you can issue the same statement by using %s placeholder markers and binding the appropri-
ate values to them:
cursor.execute ("""
UPDATE animal SET name = %s
WHERE name = %s
""", ("snake", "turtle"))
print "Number of rows updated: %d" % cursor.rowcount
Note the following points about the form of the preceding execute() call:
• The %s placeholder marker should occur once for each value that is to be inserted into the statement
string.
• No quotes should be placed around the %s markers; MySQLdb supplies quotes for you as necessary.
• Following the statement string argument to execute(), provide a tuple containing the values to be
Revision date: 2006-09-17 Printed: 2006-09-17
7. -7- Writing MySQL Scripts with Python DB-API
bound to the placeholders, in the order they should appear within the string. If you have only a single
value x, specify it as (x,) to indicate a single-element tuple.
• Bind the Python None value to a placeholder to insert an SQL NULL value into the statement.
After issuing the statements, animal.py closes the cursor, commits the changes, and disconnects from the
server:
cursor.close ()
conn.commit ()
conn.close ()
The connection object commit() method commits any outstanding changes in the current transaction to
make them permanent in the database. In DB-API, connections begin with autocommit mode disabled, so
you must call commit() before disconnecting or changes may be lost.
If the animal table is a MyISAM table, commit() has no effect: MyISAM is a non-transactional storage
engine, so changes to MyISAM tables take effect immediately regardless of the autocommit mode. How-
ever, if animal uses a transactional storage engine such as InnoDB, failure to invoke commit() results
in an implicit transaction rollback when you disconnect. For example, if you add ENGINE=InnoDB to the
end of the CREATE TABLE statement and remove the commit() invocation near the end of the script,
you’ll find that animal is empty after the script runs.
For scripts that only retrieve data, no changes need to be committed and commit() is unnecessary.
Portability Notes
If you want to port a MySQLdb-based DB-API script for use with a different database, sources of non-
portability occur anywhere that the driver name might be used:
• The import statement that imports the driver module. This must be changed to import a different
driver.
• The connect() call that connects to the database server. The connect() method is accessed
through the name of the driver modules, so the driver name needs to be changed. In addition, the con-
nect() argument syntax may vary between drivers.
• Exception handling. The exception class named on except clauses is referenced through the driver
name.
Another type of non-portability that does not involve the driver name concerns the use of placeholders. The
DB-API specification allows for several placeholder syntaxes, and some drivers use a syntax that differs
from the one supported by MySQLdb.
Resources
The scripts that are used for examples in this document can be downloaded from the following location:
http://www.kitebird.com/articles/
You may find the following additional resources helpful for using Python DB-API and the MySQLdb
driver:
• Andy Dustman, author of the MySQLdb module, has a site at:
http://dustman.net/andy/python/
That site is the best place to read the MySQLdb documentation and FAQ online. It also has links to
Revision date: 2006-09-17 Printed: 2006-09-17
8. Writing MySQL Scripts with Python DB-API 8-
Debian and Windows binary distributions. To get source code or Linux RPMs, visit the MySQLdb
SourceForge repository at:
http://sourceforge.net/projects/mysql-python
• MySQL Cookbook includes Python DB-API among the database programming interfaces that it covers:
http://www.kitebird.com/mysql-cookbook
http://www.oreilly.com/catalog/mysqlckbk/
• The Python web site has installers for the Python language processor, should you be running on a sys-
tem that doesn’t already have it installed:
http://www.python.org/
• The database SIG (special interest group) area on the Python web site contains additional DB-API
information:
http://www.python.org/sigs/db-sig/
• The animal table used by the animal.py script is also used in the PEAR DB document at the Kitebird
site:
http://www.kitebird.com/articles/
You might find it instructive to compare that document with this one to see how DB-API and PEAR DB
are similar or different in their approaches to database access.
Appendix
The full source code for the animal.py script is shown here:
#!/usr/bin/python
# animal.py - create animal table and
# retrieve information from it
import sys
import MySQLdb
# connect to the MySQL server
try:
conn = MySQLdb.connect (host = "localhost",
user = "testuser",
passwd = "testpass",
db = "test")
except MySQLdb.Error, e:
print "Error %d: %s" % (e.args[0], e.args[1])
sys.exit (1)
# create the animal table and populate it
try:
cursor = conn.cursor ()
cursor.execute ("DROP TABLE IF EXISTS animal")
cursor.execute ("""
CREATE TABLE animal
(
name CHAR(40),
category CHAR(40)
)
""")
cursor.execute ("""
Revision date: 2006-09-17 Printed: 2006-09-17
9. -9- Writing MySQL Scripts with Python DB-API
INSERT INTO animal (name, category)
VALUES
(’snake’, ’reptile’),
(’frog’, ’amphibian’),
(’tuna’, ’fish’),
(’racoon’, ’mammal’)
""")
print "Number of rows inserted: %d" % cursor.rowcount
# perform a fetch loop using fetchone()
cursor.execute ("SELECT name, category FROM animal")
while (1):
row = cursor.fetchone ()
if row == None:
break
print "%s, %s" % (row[0], row[1])
print "Number of rows returned: %d" % cursor.rowcount
# perform a fetch loop using fetchall()
cursor.execute ("SELECT name, category FROM animal")
rows = cursor.fetchall ()
for row in rows:
print "%s, %s" % (row[0], row[1])
print "Number of rows returned: %d" % cursor.rowcount
# issue a statement that changes the name by including data values
# literally in the statement string, then change the name back
# by using placeholders
cursor.execute ("""
UPDATE animal SET name = ’turtle’
WHERE name = ’snake’
""")
print "Number of rows updated: %d" % cursor.rowcount
cursor.execute ("""
UPDATE animal SET name = %s
WHERE name = %s
""", ("snake", "turtle"))
print "Number of rows updated: %d" % cursor.rowcount
# create a dictionary cursor so that column values
# can be accessed by name rather than by position
cursor.close ()
cursor = conn.cursor (MySQLdb.cursors.DictCursor)
cursor.execute ("SELECT name, category FROM animal")
result_set = cursor.fetchall ()
for row in result_set:
print "%s, %s" % (row["name"], row["category"])
print "Number of rows returned: %d" % cursor.rowcount
cursor.close ()
except MySQLdb.Error, e:
print "Error %d: %s" % (e.args[0], e.args[1])
sys.exit (1)
conn.commit ()
conn.close ()
Revision date: 2006-09-17 Printed: 2006-09-17
10. Writing MySQL Scripts with Python DB-API 10 -
Acknowledgment
The original version of this document was written for NuSphere Corporation. The current version is an
updated revision of the original.
Revision History
• 1.00—Original version.
• 1.01, 2003-01-24—Minor revisions.
• 1.02, 2006-09-17—Bring up to date for MySQLdb 1.2.1. Add information about autocommit mode and
the commit() method.
Revision date: 2006-09-17 Printed: 2006-09-17