Python:如何使用MySQL创建表?代码示例

2021年3月23日14:58:25 发表评论 714 次浏览

MySQL是关系数据库管理系统(RDBMS), 而结构化查询语言(SQL)是用于使用命令(即从数据库创建, 插入, 更新和删除数据)处理RDBMS的语言。SQL命令不区分大小写即创建并创建表示相同的命令。

安装

请按照下面提到的过程为python MySQL安装依赖项

  1. 使用命令提示符导航到python脚本目录。
  2. 执行命令
    pip install mysql-connector
    

Python Mysql连接器模块方法

connect():

此功能用于建立与MySQL服务器的连接。

以下是用于启动连接的参数。

  1. 用户:与用于验证连接的MySQL服务器关联的用户名
  2. 密码:与用于验证的用户名关联的密码
  3. 数据库:MySQL中用于创建表的数据库

光标()

游标是执行SQL命令时在系统内存中创建的工作空间, 该内存是临时的, 游标连接在整个会话/生命周期内都受到限制, 并且将执行命令

execute()

execute函数以一个SQL查询作为参数并执行。查询是用于创建, 插入, 检索, 更新, 删除等的任何SQL命令。

数据库

数据库是将信息组织成多个表的组织。数据库的组织方式使操作数据变得容易, 即创建, 插入, 更新和删除等。

创建数据库的SQL命令:

CREATE DATABASE ;

例子:考虑以下在MySQL中创建数据库的示例(例如:college)

# Python code for creating Database
# Host: It is the server name. It will be 
# "localhost" if you are using localhost database
  
import mysql.connector as SQLC
# Establishing connection with the SQL 
  
DataBase = SQLC.connect(
   host = "server name" , user = "user name" , password = "password"
)
# Cursor to the database
Cursor = DataBase.cursor()
  
Cursor.execute( "CREATE DATABASE College" )
print ( "College Data base is created" )

输出:

College Data base is created
Python:MySQL创建表1

  1. 表是以行和列的形式组织的数据的集合。表存在于数据库中。
  2. 行也称为元组
  3. 列称为表的属性

创建表的SQL命令:

CREATE TABLE
(
     column_name_1 column_Data_type, column_name_2 column_Data_type, :
     :
     column_name_n column_Data_type
);

SQL数据类型

数据类型用于定义将存储在表单元格中的数据类型。

数据类型的不同类型

  1. 数字
  2. 字元/字串
  3. 约会时间。
  4. Unicode字符/字符串
  5. 二元

除上述数据类型外, MySQL中还有其他各种数据类型, 其中包括CLOB, BLOB, JSON, XML格式.

考虑下面提到的用于创建"学生"表的python代码, 该表包含先前创建的数据库"学院"中的两个"列名"和"卷号"。

# Python code for creating Table in the Database
# Host: It is the server name. It will be "localhost"
# if you are using localhost database
  
import mysql.connectors as SQLC
def CreateTable():
       
      # Connecting To the Database in Localhost
      DataBase = SQLC.connect(
                  host = "server name" , user = "user name" , password = "password" , database = "College"
                )
  
      # Cursor to the database
      Cursor = DataBase.cursor()
  
      # Query for Creating the table
      # The student table contains two columns Name and
      # Roll number of data types varchar i.e to store string
      # and Roll number of the integer data type.
      TableName = "CREATE TABLE Student 
                 (
                     Name VARCHAR( 255 ), Roll_no int
                 );"
  
      Cursor.execute(TableName)
      print ( "Student Table is Created in the Database" )
      return 
  
# Calling CreateTable function 
CreateTable()

输出:

Student Table is Created in the Database

注意怪胎!巩固你的基础Python编程基础课程和学习基础知识。

首先, 你的面试准备可通过以下方式增强你的数据结构概念:Python DS课程。


木子山

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: