In this second part we will learn how to CREATE a TABLE and to use the SELECT. There is a first post which explains how to connect to the MySQL Server and how to Create a Database which are the two first steps of this series. If you have not yet gone through the first part follow this link: https://blog.nissaar.com/using-mysql-with-python-part1
By now your code should at least look like this:
And now we will proceed further.
CREATE TABLE statement is used to create a table in the database. The SQL Syntax is as follows:
CREATE TABLE tablename (
tablename is the name to be given to the table
column1, column2, column3 are the names to be given to the columns
datatype is just as the name states (type of data) which the columns will hold; they can be characters, numbers, date etc… They are specified with the maximum
length of characters (maximum is 255).
Usually there must be a column which will hold the PRIMARY KEY which is a UNIQUE value. Many prefer to name the column as
id. When creating the table it must be specified which column will hold the
We will take as example the bio of a person to proceed.
Create table using Python
The following code will go below the codes in the picture at the top.
sql = "CREATE TABLE test1 (id INT AUTO_INCREMENT PRIMARY KEY, Last_Name varchar(255), First_Name varchar(255), Age int, Country varchar(255) );"
In this case a
columns Last_name, First_Name, Age, Country and there respective
datatypes will be created.
primary key in this case is
id with datatype
AUTO_INCREMENT is used so that it will not be necessary to specify the
primary key each time, it will automatically be incremented to have a unique value.
A table like this should have been created.
In this method everything is in the code.