Using SQL in PyCharm

PyCharm allows us to write, edit, and run SQL commands within a console. In addition to being able to work with the console as a simple text file, PyCharm users also have the added bonus of code completion and syntax checking when using the console.

Let's see an example of this by following the steps mentioned here:

  1. First, to open the console in our PyCharm workspace, click on the Jump to Console icon from the toolbar of the Database panel as illustrated here:

Opening a database console
  1. If there is more than one available console within your project, select the one that corresponds to the database that you would like to work with. In the current Chinook example, we simply have a SQLite database, so the corresponding console will be opened in the editor.

To send a query to your database and have it executed, enter the actual query into the console. For example, enter the following SQL command: 

SELECT a.Title FROM Album a

This command queries and returns all the entries in the Title column of the Album table. Note that the a variable in the command here is being used as a placeholder for Album. In other words, a.Title is a shorthand for Album.Title, which, again, corresponds to the data in the Title column of Album.
Similar to what we have discussed for Python, JavaScript, and HTML, it is recommended that you manually type in the command to experience PyCharm's code completion support, in this case, for SQL. Now, let's execute the query and see what is returned afterward:

  1. Click on the Execute button in the toolbar of the console:

Executing a query
  1. As the query executes and returns, PyCharm's Database Console panel will pop up (most likely at the bottom of your project window), displaying the output of our query:

The output from database queries

This panel will contain any output produced by your database queries. You might also notice that there are multiple tabs within this panel—the tab in the preceding screenshot displays the actual result of the executed query, while the Output tab (to the left) contains performance-related information about the queries.

Additionally, you can save SQL commands in a console to a SQL script file; simply go to File | Save as and select the location to which you would like to save the file:

Saving SQL queries

Conversely, we can open a given SQL file, edit, and execute it in our PyCharm console in the same way. We have seen this ability to work with scripts of different languages simultaneously in the PyCharm editor multiple times before with JavaScript, HTML, and Jinja in previous chapters; this ability is quite powerful while working with databases as well.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset