How to create a database in Python.

Step 1: Connect database

db = pymysql.connect(host='localhost',port =3306,user='root',passwd='root',db='sys',charset='utf8' )

Step 2: Create the table.

SQL = """CREATE TABLE `income` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `datetime` varchar(20) DEFAULT NULL,
  `ironincome` decimal(20,2) DEFAULT NULL,
  `generalincome` decimal(20,2) DEFAULT NULL,
  `baiincome` decimal(20,2) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
"""

The third step: Close the table.

cursor.execute(SQL)

db.close()

The complete code is as follows:

# -*- coding:utf-8 -*-
import pymysql

# Open Database
db = pymysql.connect(host='localhost',port =3306,user='root',passwd='root',db='sys',charset='utf8' )

# Use cursor () method to get the cursor operation
cursor = db.cursor()

# If the data table already exists using the execute () method to delete Table
cursor.execute("drop table if EXISTS income")

# Create a database SQL statement
#time,ironincome,general_income,baiincome
SQL = """CREATE TABLE `income` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `datetime` varchar(20) DEFAULT NULL,
  `ironincome` decimal(20,2) DEFAULT NULL,
  `generalincome` decimal(20,2) DEFAULT NULL,
  `baiincome` decimal(20,2) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
"""
cursor.execute(SQL)

db.close()

  

 

Guess you like

Origin www.cnblogs.com/hewanli/p/11684360.html