One place for hosting & domains

      Store

      Getting Started with WooCommerce: Build Your Own Store Today


      Whether it’s selling vintage treasures or making millions from digital products, setting up your own online store can be really exciting. What’s more, you don’t need to be a tech expert to get started.

      In fact, all you need is a WordPress site equipped with WooCommerce. This powerful plugin turns your site into an e-commerce store faster than you can say “ka-ching.”

      Of course, there’s still a small learning curve involved. To help you get started, we’ve compiled a complete introductory guide.

      Keep reading to learn why WooCommerce is so easy to use and how to set up your own store, configure products, start taking payments, and customizing your site.

      What Is WooCommerce?

      DreamHost Glossary

      WooCommerce

      WooCommerce is a WordPress plugin designed for e-commerce needs. This tool can enable website owners to start selling products in a flexible, customizable online store.

      Read More

      WooCommerce is a popular, free plugin that allows you to create an online store on your WordPress site.

      First launched in 2011, WooCommerce was later acquired by Automattic in 2015, essentially making it the officially supported WordPress e-commerce plugin. Since then, it has seen pretty rapid growth.

      According to statistics collected by Barn2, WooCommerce powers almost 41% of all e-commerce websites. This makes it the most popular e-commerce solution by far, almost double its closest competitor (Shopify).

      Why WooCommerce Is The Ideal Choice For Your Online Store

      So, what is all the hubbub about? To understand why WooCommerce is so popular, it’s worth taking a closer look at what this plugin offers.

      For a start, WooCommerce is easy to install and configure. Using the basic free plugin on default settings, you can set up a store in less than an hour.

      At the same time, WooCommerce offers loads of control for more experienced sellers. You can play around with product costs, item details, shipping fees, taxes, stock levels, images, and much more.

      You can also tailor the checkout process to suit your needs, thanks to customizable carts, geolocation features, and several different payment gateways.

      WooCommerce is also very scalable. As your site grows over time, the plugin makes it easy to add powerful features and expand your store.

      WooCommerce Vs. Other E-commerce Solutions

      This all looks great on paper, but you might be wondering how WooCommerce stacks up against the competition.

      Based on popularity, the two closest competitors are Shopify (a standalone e-commerce platform) and Magento (a Content Management System or CMS).

      DreamHost Glossary

      Content Management System (CMS)

      A Content Management System (CMS) is a software or application that provides a user-friendly interface for you to design, create, manage, and publish content.

      Read More

      Let’s compare WooCommerce to these major players on three key factors:

      Pricing

      WooCommerce is an open-source e-commerce platform that is 100% free. While you can extend the core platform with premium add-ons, the only necessary expense is web hosting, which starts at just $2.95 per month with DreamHost.

      In contrast, Shopify and Magento charge monthly fees plus transaction fees. That adds up over time and can really cut into your profits.

      Ease Of Use

      You only need a basic understanding of WordPress to set up an online store using WooCommerce. The admin area allows drag-and-drop building and editing.

      Shopify also offers an intuitive dashboard, but customization can get complicated. Meanwhile, configuring a Magento store requires more technical knowledge.

      Features

      You name it, WooCommerce has it: secure checkout, shipping calculators, product management, coupon codes, customer reviews, robust reporting, and more.

      Shopify and Magento both offer similar functionality, but popular extensions and apps often come at extra cost. Most WooCommerce extensions are free, and even premium extensions tend to be affordable.

      The bottom line: WooCommerce beats its closest competitors on pricing, while matching features. Plus, you get all the benefits of WordPress.

      Get Content Delivered Straight to Your Inbox

      Subscribe to our blog and receive great content just like this delivered straight to your inbox.

      How To Set Up A Store With WooCommerce (5-Step Guide)

      If you decide to launch your new venture with WooCommerce, the next step is to set up your store.

      As we mentioned, WooCommerce is pretty easy to install and configure. But if you would feel more confident with a little guidance, here’s a complete step-by-step tutorial:

      Step 1: Install The WooCommerce Plugin

      The first step toward building your online business is to install WooCommerce.

      Start by logging in to your WordPress site and selecting Plugins > Add New Plugin in the left sidebar.

      close up of the wordpress nav menu showing the selection for "add new plugin"

      Use the search bar to find WooCommerce in the official Plugin Directory. The one you want should be the first result.

      Click the Install Now button.

      woocommerce plugin screenshot pointing out the "install now" button in the right-hand corner of the box

      Once the installation process is complete, activate the plugin. You will then see a WooCommerce appear in the left sidebar. This is where you’ll manage all your store settings.

      Step 2: Follow The Setup Wizard

      If you open WooCommerce from the sidebar, the plugin will encourage you to launch the setup wizard.

      screenshot of the "Welcome to Woo!" message with a button to "Set up my store"

      After the welcome screen, the wizard will ask you whether you’re setting up a store for the first time or already selling online. Choose the relevant option.

      Next, add your store details: name, location, industry, and email. Later on, this information will appear on all your invoices, packing slips, and confirmation emails.

      Once your business details are entered, you can choose to install the suggested extensions or wait until later.

      Finally, click Continue to launch your online storefront.

      Step 3: Add Products To Your Store

      We’re ready to sell, right? Well, not quite. Your store needs some products if you’re going to make any money.

      To begin populating your new store, tap Add Products on the start screen.

      screenshot of the status bar showing "Let's get you started" and the step to "add product to sell" by clicking the blue "add products" button

      Select the relevant product type. Choose “Variable product “if your product comes in different variations (e.g., sizes and/or colors).

      Next, fill out the key product details.

      • Title and description: Include keywords that customers might search for.
      • Pricing: Set regular and sale prices.
      • Product images: High-quality photos will help you make sales.
      • Product categories: Decide how products are grouped in site navigation.
      • Inventory: Track your stock and set up alerts.
      • Shipping: Add the product weight and dimensions to calculate shipping rates.

      If you’re setting up a “Variable” product, make sure to add the different product variations under the Attributes tab.

      Finish by publishing your new product. If you want to add more products, you can use your first product as a template. Duplicate the first product listing and edit the content.

      Step 4: Select Your Payment Options

      To make money from your products, you need to provide customers with a way to pay for their purchases. Luckily, WooCommerce makes it pretty easy to handle transactions.

      The most convenient path here is WooCommerce Payments. Powered by Stripe, this system is completely integrated with the WooCommerce system.

      To configure this payment option, navigate to WooCommerce > Home and select Set up payments. Then, click on Get started and follow the setup instructions.

      If you want to provide customers with an alternative, Stripe and PayPal are good options. Both allow you to accept all major credit cards, plus Google Pay and Apple Pay. The latter also allows PayPal users to pay directly from their account, which can increase conversion rates significantly.

      Other online payment options include:

      • AliPay
      • Skrill
      • Braintree
      • Authorize.net
      • Amazon Pay
      • Square

      You can enable several popular payment methods in the Set up payments area. For more granular control, navigate to WooCommerce > Settings and select the Payments tab.

      screenshot of the payment methods setting showing the toggle to enable options for WooPayments, direct bank transfer, check payments, and cash on delivery

      To add a new third-party processor, you will need to install the matching extension and set up a payment account. Be sure to check the fees associated with each gateway, because they vary significantly.

      Step 5: Configure Sales Tax And Shipping Options

      Both tax and shipping can cause headaches for new business owners. Luckily, WooCommerce makes it fairly easy to collect the right amount and send shipments to the right address.

      Once you’ve set up payments, the setup guide will prompt you to “Add tax rates.”

      screenshot of the set up wizard showing "add tax rates" as the number four step

      Start by visiting WooCommerce > Home and find the option to Add tax rates. Here, you have two choices:

      1. Set up WooCommerce Tax, an extension that automates tax calculations.
      2. Set up your tax rates manually (see the small link at the bottom of the page).

      WooCommerce Tax is definitely the easier option here. You can set it up in a couple of minutes by following the on-screen instructions.

      If you prefer to set tax rates yourself, you can head to WooCommerce > Settings and select the Tax tab.

      • While you’re still inside the Tax tab, select Standard Rates from the sub-menu at the top.
      • Add tax rates by country, state, or even zip code. Use the Insert Row button to create a new line and then input your data.
      • Finally, save your changes.

      If you’re only selling digital products or affiliate items, you can skip to the next step. But if your store offers physical items that need to be mailed, you should take a minute to set up your shipping options.

      Head to WooCommerce > Settings and choose the Shipping tab. You’ll see the U.S. already added if the address of your business is in the United States.

      screenshot of the zone name, region, and shipping methods available for each zone with the United States as a default

      But you can add more. At the top of the page, select Shipping zones. Click Add zone.

      Shipping zones are geographical areas that you define as having the same shipping requirements, including carriers and types of shipping.

      To configure your new zone:

      • Add a name for the region. Make it descriptive.
      • In the Zone regions field, choose the locations you want to be included in the zone.
      • Choose which shipping methods should be available in the new zone: free shipping, flat rate, or local pickup.
      • Finally, click on each method to adjust the cost and any specific requirements (e.g. minimum order for free shipping).
      • Don’t leave your zone hanging. Hit that save button.

      And just like that, you’re ready for lift-off! Your store now has the logic to handle taxes like a seasoned accountant and ship packages as if it’s got its own delivery fleet.

      Remember to test everything once you’re done. Make a mock purchase to see if taxes and shipping costs are added correctly. It’s a good idea to run a system check before the real deal.

      How To Customize Your WooCommerce Store

      We could literally spend a couple of days talking about all the ways you can customize your new WooCommerce store.

      Exploring the built-in options should keep you busy for a while, but when you’re ready to take your store to the next level, there are two types of upgrades to check out: themes and plugins.

      WooCommerce Themes

      WooCommerce works well with just about any WordPress theme. However, there are plenty of themes specifically created for sites that use WooCommerce.

      These themes help you customize your store’s appearance to match the rest of your online presence. Some even add new functionality related to WooCommerce, such as custom post types.

      Most WooCommerce themes are based on the official Storefront theme:

      screenshot of the storefront woocommerce theme

      This theme is developed by the team behind WooCommerce, so you can be sure that it’s secure and that the integration is bullet-proof. Storefront is also free, which is always a plus.

      While this theme works well on its own, it can be further expanded using one of several child themes.

      If you’re not aware, a child theme builds on an existing theme (its “parent”), enabling you to make changes to the parent theme without editing it directly.

      In addition to Storefront and its child themes, you can find a wide range of WooCommerce-ready premium themes. Many of these are specialized for different types of stores.

      For example, Electro is specifically built for creating electronics shops, while the Motor theme is tailored toward car dealerships. Regardless of your business and tastes, you should be able to find a theme that works perfectly for you.

      WooCommerce Extensions

      Once you’ve picked out a theme for your store, it’s time to consider whether you need some additional features. 

      WooCommerce extensions allow you to introduce new functionality to your WordPress store. While they work very much like WordPress plugins, they are specifically created to integrate with WooCommerce.

      Some extensions are free to use, while others require a one-time payment or a regular subscription fee. Either way, you can use them to enhance your store with advanced features.

      There are hundreds of extensions today, from sales analysis tools to security plugins. We’re going to take a look at a few of the best options for first-time WooCommerce users.

      1. WooCommerce Google Analytics

      screenshot of the woocommerce google analytics plugin for WP

      WooCommerce Google Analytics enables you to use Google Analytics to track your store’s performance. This extension can help you understand your customers’ journey, including how they found your site and which products they’re most interested in. You can then use this data to optimize your sales funnel.

      Key Features:

      • Tracks session length, users, and referrers.
      • Highlights which areas of your store perform well and which need improvement.
      • Helps you understand customer behavior and product popularity.

      Pricing: WooCommerce Google Analytics is a free extension, but it does offer a premium version as well, starting at $79 per year for a single site. Both extensions also require a free Google Analytics account.

      2. WooCommerce Subscriptions

      woocommerce subscriptions plugin for wp screenshot

      WooCommerce Subscriptions lets you create products that can be unlocked with recurring payments. The extension works both for physical products, such as a monthly subscription box, and virtual products or services.

      Key Features:

      • Enables you to choose your payment schedule from several options.
      • Offers more than 25 popular payment gateways.
      • Supports automatic subscription renewal emails for both you and your customers.

      Pricing: WooCommerce Subscriptions starts at $239 per year for a single site.

      3. WooCommerce Zapier

      screenshot of the woocommerce for zapier extension

      WooCommerce Zapier is a great solution for integrating your store with third-party services. With this one extension, you can connect WooCommerce with MailChimp, YouTube, Dropbox, Google Drive, and many other platforms.

      Key Features:

      • Integrates with over 1,000 third-party services.
      • Enables you to configure automation to save time.
      • Provides performance reports through the “Digest by Zapier” feature.

      Pricing: WooCommerce Zapier prices start at $79 per year for a single site.

      4. Square For WooCommerce

      screenshot of the square for woocommerce extension

      Square for WooCommerce enhances your store’s payment options, both online and in person. The extension is very easy to install, and you’ll be able to accept payment within minutes. Square is compatible with all credit and debit cards in the US, UK, Australia, Canada, and Japan.

      Key Features:

      • Makes it easier to accept payments from various sources.
      • Deposits your funds quickly, within 1-2 business days.
      • Enables you to quickly sync your Square and WooCommerce accounts.

      Pricing: Square for WooCommerce is a free extension that requires a Square account.

      5 Tips For Growing A Successful WooCommerce Store

      Now your store is complete, you can concentrate on growing your new business. Here are some key tips for attracting customers and making sales:

      1. Use Coupon Codes And Promotions To Boost Sales

      Everyone loves a good deal. As a store owner, you can tap into this universal truth by offering coupon codes and promotions. They’re not just money-savers for your customers — they’re sale-makers for you.

      Create time-sensitive discounts, bundle deals, or loyalty rewards. You can also give away free gift cards with purchases over a certain size. These little incentives can be enough to persuade window shoppers to make a purchase.

      To create promotional coupon codes, select Marketing > Coupons from the left-hand sidebar.

      2. Get More Customers With Search Engine Optimization

      Your store is a needle in the Internet haystack. SEO (search engine optimization) can help you emerge from the pile, so that more customers can find your site.

      DreamHost Glossary

      SEO

      Search Engine Optimization (SEO) is the practice of improving a site’s ranking in search results. Search results are aggregated based on a number of factors, including a site’s relevance and quality. Optimizing your site for these factors can help boost your rankings.

      Read More

      To reap the benefits here, make sure to do your homework with keyword research. Find out which phrases your customers are searching for, and then weave those magic words into your product descriptions, titles, and metadata. Use a plugin like Yoast SEO to guide you.

      3. Use Analytics To Understand Your Buyers

      You don’t need a crystal ball to figure out which products to stock. Tools like Google Analytics can reveal valuable insights about your buyers.

      Find out where they come from, how long they hang around, and what catches their eye. With this intel, you can better understand who your future customers are likely to be — and tailor your storefront to suit.

      4. Maintain Proper Security

      Your online store is your kingdom, and every castle needs defenses. Way too many small businesses fall victim to cyber attacks, leading to plenty of financial pain.

      To avoid this fate, regularly update your WooCommerce and plugins.

      Nerd Note: WordPress actually offers automatic updates for most plugins via Plugins > Enable auto-updates.

      While you’re at it, enable data backups. This will allow you to restore your site quickly if anyone manages to break in.

      5. Create Custom Solutions With Blocks

      WooCommerce Blocks allows you to create custom-designed pages without needing a PhD in coding.

      Want a checkout that’s smoother than butter? There’s a block for that. Eyeing a product grid that’s cleaner than your Sunday best? Blocks have got you covered. Experiment with them to craft a store that perfectly matches your needs.

      WooCommerce FAQs

      Still have questions? We have answers:

      How much does WooCommerce cost?

      For self-hosted e-commerce sites, the WooCommerce plugin is completely free. As such, you only need to cover your hosting requirements and your domain. You can also extend the core platform by paying for premium plugins and themes.

      Do I need hosting for WooCommerce?

      Yes. Or more accurately, you need a hosted website. Remember that WooCommerce is actually a plugin for WordPress, not a standalone store builder.

      Can you dropship with WooCommerce?

      Although WooCommerce doesn’t natively support dropshipping, you can introduce this feature via the WooCommerce Dropshipping premium plugin.

      Can You Sell On WordPress Without WooCommerce?

      Although WooCommerce is probably the best e-commerce plugin, it isn’t the only option. Search in the official Plugin Directory, and you will find plenty of alternative options.

      Start An Online Store Today

      If you want to use your WordPress site to sell goods and services, WooCommerce is by far your best option.

      It’s the most popular e-commerce plugin for a reason, and it makes it incredibly easy for beginners and experienced users alike to open an online store. The basic WooCommerce plugin lets you build a successful business, and you can improve it even further using themes and extensions.

      But remember, building your e-commerce website is just the first step. You’ll also need to make sure that your store is always accessible and that you provide a great customer experience. That starts with choosing a reliable hosting provider.

      With DreamHost, every plan is backed by a 100% uptime guarantee. And with our dedicated WooCommerce plans, your site runs on optimized servers — meaning lightning-fast loading times.

      Check out our hosting plans today to begin your online retail journey!



      Source link

      How To Store WordPress Assets on DigitalOcean Spaces With Ubuntu 20.04


      Introduction

      DigitalOcean Spaces is an object storage service that can be used to store large amounts of diverse, unstructured data. WordPress sites, which often include image and video assets, can be good candidates for object storage solutions. Using object storage for these types of static resources can optimize site performance by freeing up space and resources on your servers. For more information about object storage and WordPress check out our tutorial on How To Back Up a WordPress Site to Spaces.

      In this tutorial, you’ll learn how to use a WordPress plugin that works directly with DigitalOcean Spaces as the primary asset store. The DigitalOcean Spaces Sync plugin routes the data of our WordPress media library to Spaces and provides you with various configuration options based on your needs, streamlining the process of using object storage with your WordPress instance.

      Prerequisites

      This tutorial assumes that you have a WordPress instance on a server you’ll use as a DigitalOcean Space. If you do not have this set up, you can complete the following:

      With these prerequisites in place, you’re ready to begin using this plugin.

      Modifying WordPress Permissions

      Throughout this tutorial, you will be working with the wp-content/uploads folder in your WordPress project, so it is important that this folder exists and has the correct permissions. You can create it with the mkdir command using the -p flag in order to create the folder if it doesn’t exist, and avoid throwing an error if it does:

      • sudo mkdir -p /var/www/html/wp-content/uploads

      You can now set permissions on the folder. First, set the ownership to your user (you will use sammy here, but be sure to use your non-root sudo user), and group ownership to the www-data group:

      • sudo chown -R sammy:www-data /var/www/html/wp-content/uploads

      Next, establish the permissions that will give the web server write access to this folder:

      • sudo chmod -R g+w /var/www/html/wp-content/uploads

      You will now be able to use our plugins to create a store in object storage for the assets in the wp-content/uploads folder, and to engage with your assets from the WordPress interface.

      Installing DigitalOcean Spaces Sync

      The first step in using DigitalOcean Spaces Sync will be to install it in your WordPress folder. You can navigate to the plugin folder within our WordPress directory:

      • cd /var/www/html/wp-content/plugins

      From here, install DigitalOcean Spaces Sync using the wp command:

      • wp plugin install do-spaces-sync

      To activate the plugin, you can run:

      • wp plugin activate do-spaces-sync

      From here, navigate to the plugins tab on the left-hand side of our WordPress administrative dashboard:

      WordPress Plugin Tab

      You should see DigitalOcean Spaces Sync in your list of activated plugins:

      Spaces Sync Plugin Screen

      To manage the settings for DigitalOcean Spaces Sync, navigate to our Settings tab, and select DigitalOcean Spaces Sync from the menu:

      Settings Tab

      DigitalOcean Spaces Sync will now give you options to configure your asset storage:

      DO Spaces Sync Configuration

      The Connection Settings field in the top half of the screen asks for your Spaces Access Key and Secret. It will then ask for your Container, which will be the name of your Space, and the Endpoint.

      You can determine the endpoint of your Space based on its URL. For example, if the URL of your Space is https://example-name.nyc3.digitaloceanspaces.com, then example-name will be your bucket/container, and nyc3.digitaloceanspaces.com will be your endpoint.

      In the plugin’s interface, the Endpoint section will be pre-filled with the default https://ams3.digitaloceanspaces.com. You should modify this endpoint if your Space lives in another region.

      Next, you will be asked for File & Path Settings. In the field marked Full URL-path to files, you can input either a storage public domain, if your files will be stored only on your Space, or a full URL path, if you will store them on your Space and server.

      For example, if your WordPress project is located in /var/www/html, and you want to store files on both your server and Space, then you would enter:

      • http://your_server_ip/wp-content/uploads in the Full URL-path to files field
      • /var/www/html/wp-content/uploads in the Local path field

      The Storage prefix and Filemask settings are prefilled, and do not need to be modified unless you would like to specify certain types of files for your sync.

      You will cover the specifics of storing files on your server and Space and on your Space alone in the following sections.

      Syncing and Saving Files in Multiple Locations

      DigitalOcean Spaces Sync offers the option of saving files to your server while also syncing them to your Space. This utility can be helpful if you need to keep files on your server, but would also like backups stored elsewhere. For this tutorial, you will go through the process of syncing a file to your Space while keeping it on your server. For the purposes of this example, you will assume that you have a file called sammy10x10.png that you would like to store in your media library and on your Space.

      First, navigate to the Settings tab on your WordPress administrative dashboard, and select DigitalOcean Spaces Sync from the menu of presented options.

      Next, in the Connections Settings field, enter your Spaces Key and Secret, followed by your Container and Endpoint. Remember, if the URL of your Space is https://example-name.nyc3.digitaloceanspaces.com, then example-name will be your Container, and nyc3.digitaloceanspaces.com will be your Endpoint. Test your connections by clicking the Check the Connection button at the bottom of the Connection Settings field:

      Check Connection Button

      Now you are ready to fill out the File & Path Settings.

      In the Full URL-path to files field you can enter our full URL path, since you are saving your file on your server and on your Space. You’ll use your server’s IP here, but if you have a domain, you can swap out the IP address for your domain name. For more about registering domains with DigitalOcean, see our tutorial on How To Set Up a Host Name with DigitalOcean. In this case, the Full URL-path to files will be http://your_server_ip/wp-content/uploads.

      Next, you will fill out the Local path field with the local path to the uploads directory: /var/www/html/wp-content/uploads.

      Because you are working with a single file, you do not need to modify the Storage prefix and Filemask sections. As your WordPress media library grows in size and variety, you can modify this setting to target individual file types using wildcards and extensions such as *.png in the Filemask field.

      Your final File & Path Settings will look like this:

      Sync Server and Cloud

      Be sure to save your configuration changes by clicking the Save Changes button at the bottom of the screen.

      Now you can add the file, sammy10x10.png, to our WordPress media library. You’ll use the wp media import command, which will import the file from your home directory to your WordPress media library. In this case, your home directory will belong to sammy, but in your case this will be your non-root sudo user. As you move the file, you will use the --path parameter to specify the location of our WordPress project:

      • wp media import --path=/var/www/html/ /home/sammy/sammy10x10.png

      Looking at the WordPress interface, you should now see the file in your Media Library. You can navigate there by following the Media Library tab on the left side of our WordPress administrative dashboard:

      Media Library Tab

      If you navigate to your Spaces page in the DigitalOcean control panel, you should also see the file in your Space.

      Finally, you can navigate to our wp-content/uploads folder, where WordPress will have created a sub-folder with the year and month. Within this folder you should see our sammy10x10.png file.

      Storing Files on Spaces

      The DigitalOcean Spaces Sync plugin has an additional option that will allow you to store files only on your Space, in case you would like to optimize space and resources on our server. You will work with another file, sammy-heart10x10.png, and set your DigitalOcean Spaces Sync settings so that this file will be stored only on your Space.

      First, let’s navigate back to the plugin’s main configuration page:

      DO Spaces Sync Configuration

      You can leave the Connection Settings information, but will modify the File & Path Settings. First, in the Full URL-path to files, you will write the storage public domain. Again, you will use your server IP, but you can swap this out for a domain if you have one: http://uploads.your_server_ip

      Next, navigate to Sync Settings, at the bottom of the page, and click the first box, which will allow you to “store files only in the cloud and delete after successful upload.” Your final File & Path Settings will look like this:

      Sync Cloud Only

      Be sure to save your changes by clicking the Save Changes button at the bottom of the screen.

      Back on the command line, move sammy-heart10x10.png from your user’s home directory to your Media Library using wp media import:

      • wp media import --path=/var/www/html/ /home/sammy/sammy-heart10x10.png

      If you navigate back to your WordPress interface, you will not see sammy-heart10x10.png or sammy10x10.png in your Media Library. Next, return to the command line and navigate to your wp-content/uploads directory — you should see that sammy-heart10x10.png is missing from your timestamped sub-folder.

      Finally, if you navigate to the Spaces page in the DigitalOcean control panel, you should see both files stored in your Space.

      Conclusion

      This tutorial covered two different options you can use to store your WordPress media files to DigitalOcean Spaces using DigitalOcean Spaces Sync. This plugin offers additional options for customization, which you can learn more about by reading the developer’s article “Sync your WordPress media with DigitalOcean Spaces.”

      If you would like more general information about working with Spaces, check out our introduction to DigitalOcean Spaces and our guide to best practices for performance on Spaces.



      Source link

      How To Store and Retrieve Data in MariaDB Using Python on Ubuntu 18.04


      The author selected the Tech Education Fund to receive a donation as part of the Write for DOnations program.

      Introduction

      MariaDB is an open source version of the popular MySQL relational database management system (DBMS) with a SQL interface for accessing and managing data. It is highly reliable and easy to administer, which are essential qualities of a DBMS capable of serving modern applications. With Python’s growing popularity in technologies like artificial intelligence and machine learning, MariaDB makes a good option for a database server for Python.

      In this tutorial, you will connect a Python application to a database server using the MySQL connector. This module allows you to make queries on the database server from within your application. You’ll set up MariaDB for a Python environment on Ubuntu 18.04 and write a Python script that connects to and executes queries on MariaDB.

      Prerequisites

      Before you begin this guide, you will need the following:

      Step 1 — Preparing and Installing

      In this step, you’ll create a database and a table in MariaDB.

      First, open your terminal and enter the MariaDB shell from the terminal with the following command:

      Once you’re in the MariaDB shell, your terminal prompt will change. In this tutorial, you’ll write Python to connect to an example employee database named workplace and a table named employees.

      Start by creating the workplace database:

      • CREATE DATABASE workplace;

      Next, tell MariaDB to use workplace as your current database:

      You will receive the following output, which means that every query you run after this will take effect in the workplace database:

      Output

      Database changed

      Next, create the employees table:

      • CREATE TABLE employees (first_name CHAR(35), last_name CHAR(35));

      In the table schema, the parameters first_name and a last_name are specified as character strings (CHAR) with a maximum length of 35.

      Following this, exit the MariaDB shell:

      Back in the terminal, export your MariaDB authorization credentials as environment variables:

      • export username="username"
      • export password="password"

      This technique allows you to avoid adding credentials in plain text within your script.

      You’ve set up your environment for the project. Next, you’ll begin writing your script and connect to your database.

      Step 2 — Connecting to Your Database

      In this step, you will install the MySQL Connector and set up the database.

      In your terminal, run the following command to install the Connector:

      • pip3 install mysql-connector-python

      pip is the standard package manager for Python. mysql-connector-python is the database connector Python module.

      Once you’ve successfully installed the connector, create and open a new file Python file:

      In the opened file, import the os module and the mysql.connector module using the import keyword:

      database.py

      import os
      import mysql.connector as database
      

      The as keyword here means that mysql.connector will be referenced as database in the rest of the code.

      Next, initialize the authorization credentials you exported as Python variables:

      database.py

      . . .
      username = os.environ.get("username")
      password = os.environ.get("password")
      

      Follow up and establish a database connection using the connect() method provided by database. The method takes a series of named arguments specifying your client credentials:

      database.py

      . . .
      connection = database.connect(
          user=username,
          password=password,
          host=localhost,
          database="workplace")
      

      You declare a variable named connection that holds the call to the database.connect() method. Inside the method, you assign values to the user, password, host, and database arguments. For user and password, you will reference your MariaDB authorization credentials. The host will be localhost by default if you are running the database on the same system.

      Lastly, call the cursor() method on the connection to obtain the database cursor:

      database.py

      . . .
      cursor = connection.cursor()
      

      A cursor is a database object that retrieves and also updates data, one row at a time, from a set of data.

      Leave your file open for the next step.

      Now you can connect to MariaDB with your credentials; next, you will add entries to your database using your script.

      Step 3 — Adding Data

      Using the execute() method on the database cursor, you will add entries to your database in this step.

      Define a function add_data() to accept the first and last names of an employee as arguments. Inside the function, create a try/except block. Add the following code following your cursor object:

      database.py

      . . .
      def add_data(first_name, last_name):
          try:
              statement = "INSERT INTO employees (first_name,last_name) VALUES (%s, %s)"
              data = (first_name, last_name)
              cursor.execute(statement, data)
              connection.commit()
              print("Successfully added entry to database")
          except database.Error as e:
              print(f"Error adding entry to database: {e}")
      

      You use the try and except block to catch and handle exceptions (events or errors) that disrupt the normal flow of program execution.

      Under the try block, you declare statement as a variable holding your INSERT SQL statement. The statement tells MariaDB to add to the columns first_name and last_name.

      The code syntax accepts data as parameters that reduce the chances of SQL injection. Prepared statements with parameters ensure that only given parameters are securely passed to the database as intended. Parameters are generally not injectable.

      Next you declare data as a tuple with the arguments received from the add_data function. Proceed to run the execute() method on your cursor object by passing the SQL statement and the data. After calling the execute() method, you call the commit() method on the connection to permanently save the inserted data.

      Finally, you print out a success message if this succeeds.

      In the except block, which only executes when there’s an exception, you declare database.Error as e. This variable will hold information about the type of exception or what event happened when the script breaks. You then proceed to print out an error message formatted with e to end the block using an f-string.

      After adding data to the database, you’ll next want to retrieve it. The next step will take you through the process of retrieving data.

      Step 4 — Retrieving Data

      In this step, you will write a SQL query within your Python code to retrieve data from your database.

      Using the same execute() method on the database cursor, you can retrieve a database entry.

      Define a function get_data() to accept the last name of an employee as an argument, which you will call with the execute() method with the SELECT SQL query to locate the exact row:

      database.py

      . . .
      def get_data(last_name):
          try:
            statement = "SELECT first_name, last_name FROM employees WHERE last_name=%s"
            data = (last_name,)
            cursor.execute(statement, data)
            for (first_name, last_name) in cursor:
              print(f"Successfully retrieved {first_name}, {last_name}")
          except database.Error as e:
            print(f"Error retrieving entry from database: {e}")
      

      Under the try block, you declare statement as a variable holding your SELECT SQL statement. The statement tells MariaDB to retrieve the columns first_name and last_name from the employees table when a specific last name is matched.

      Again, you use parameters to reduce the chances of SQL injection.

      Smilarly to the last function, you declare data as a tuple with last_name followed by a comma. Proceed to run the execute() method on the cursor object by passing the SQL statement and the data. Using a for loop, you iterate through the returned elements in the cursor and then print out if there are any successful matches.

      In the except block, which only executes when there is an exception, declare database.Error as e. This variable will hold information about the type of exception that occurs. You then proceed to print out an error message formatted with e to end the block.

      In the final step, you will execute your script by calling the defined functions.

      Step 5 — Running Your Script

      In this step, you will write the final piece of code to make your script executable and run it from your terminal.

      Complete your script by calling add_data() and get_data() with sample data (strings) to verify that your code is working as expected.

      If you would like to add multiple entries, you can call add_data() with further sample names of your choice.

      Once you finish working with the database make sure that you close the connection to avoid wasting resources:
      connection.close():

      database.py

      import os
      import mysql.connector as database
      
      username = os.environ.get("username")
      password = os.environ.get("password")
      
      connection = database.connect(
          user=username,
          password=password,
          host=localhost,
          database="workplace")
      
      cursor = connection.cursor()
      
      def add_data(first_name, last_name):
          try:
          statement = "INSERT INTO employees (first_name,last_name) VALUES (%s, %s)"
          data = (first_name, last_name)
            cursor.execute(statement, data)
          cursor.commit()
          print("Successfully added entry to database")
          except database.Error as e:
          print(f"Error adding entry to database: {e}")
      
      def get_data(last_name):
          try:
            statement = "SELECT first_name, last_name FROM employees WHERE last_name=%s"
            data = (last_name,)
            cursor.execute(statement, data)
            for (first_name, last_name) in cursor:
              print(f"Successfully retrieved {first_name}, {last_name}")
          except database.Error as e:
            print(f"Error retrieving entry from database: {e}")
      
      add_data("Kofi", "Doe")
      get_data("Doe")
      
      connection.close()
      

      Make sure you have indented your code correctly to avoid errors.

      In the same directory, you created the database.py file, run your script with:

      You will receive the following output:

      Output

      Successfully added entry to database Successfully retrieved Kofi, Doe

      Finally, return to MariaDB to confirm you have successfully added your entries.

      Open up the MariaDB prompt from your terminal:

      Next, tell MariaDB to switch to and use the workplace database:

      After you get the success message Database changed, proceed to query for all entries in the employees table:

      You output will be similar to the following:

      Output

      +------------+-----------+ | first_name | last_name | +------------+-----------+ | Kofi | Doe | +------------+-----------+ 1 row in set (0.00 sec)

      Putting it all together, you’ve written a script that saves and retrieves information from a MariaDB database.

      You started by importing the necessary libraries. You used mysql-connector to connect to the database and os to retrieve authorization credentials from the environment. On the database connection, you retrieved the cursor to carry out queries and structured your code into add_data and get_data functions. With your functions, you inserted data into and retrieved data from the database.

      If you wish to implement deletion, you can build a similar function with the necessary declarations, statements, and calls.

      Conclusion

      You have successfully set up a database connection to MariaDB using a Python script on Ubuntu 18.04. From here, you could use similar code in any of your Python projects in which you need to store data in a database. This guide may also be helpful for other relational databases that were developed out of MySQL.

      For more on how to accomplish your projects with Python, check out other community tutorials on Python.



      Source link