Python MySQL創建表格


Python MySQL創建表格

  1. 我們可以使用SQL的 CREATE TABLE 語句創建新表。

  2. 在我們的數據庫PythonDB中,Employee表最初將包含四列,即 name,id,salary 和 department_id

  3. 以下查詢用於創建新表

>  create table <table_name> (name varchar(20) not null, id int primary key, salary float not null, Dept_Id int not null)
  1. 案例
import mysql.connector  
  
# 創建連接對象   
myconn = mysql.connector.connect(host = "localhost", user = "root",passwd = "google",database = "PythonDB")  
  
# 創建游標對象 
cur = myconn.cursor()  
  
try:  
    # Creating a table with name Employee having four columns i.e., name, id, salary, and department id  
    cur.execute("create table Employee(name varchar(20) not null, id int(20) not null primary key, salary float not null, Dept_id int not null)")  
except:  
    myconn.rollback()  
  
myconn.close()
  • 查看是否以及創建 Employee 表

    import mysql.connector
    
    # 創建連接對象
    myconn = mysql.connector.connect(host="192.168.126.20", user="root", passwd="mysql",database="PythonDB")
    
    # 創建游標對象
    cur = myconn.cursor()
    
    cur.execute("show tables")
    
    for i in cur:
        print(i)
    
    • 輸出
    ('Employee',)
    
  • 查看表中是否以及創建好字段

    import mysql.connector
    
    # 創建連接對象
    myconn = mysql.connector.connect(host="192.168.126.20", user="root", passwd="mysql", database="PythonDB")
    
    # 創建游標對象
    cur = myconn.cursor()
    
    cur.execute("desc Employee")
    
    for i in cur:
        print(i)
    
    • 輸出
    ('name', 'varchar(20)', 'NO', '', None, '')
    ('id', 'int(20)', 'NO', 'PRI', None, '')
    ('salary', 'float', 'NO', '', None, '')
    ('Dept_id', 'int(11)', 'NO', '', None, '')
    
  • 服務器端查看Employee表信息

  1. 改變表
  • 有時,我們可能忘記創建一些列,或者我們可能需要更新表模式。如果需要,alter 語句用於更改表模式。在這里,我們將列branch_name添加到表Employee中。以下SQL查詢用於此目的
alter table Employee add branch_name varchar(20) not null
  • 示例
import mysql.connector  
  
# 創建一個連接對象 
myconn = mysql.connector.connect(host="192.168.126.20", user="root", passwd="mysql", database="PythonDB")  
  
# 創建游標對象  
cur = myconn.cursor()  
  
try:  
    # adding a column branch name to the table Employee  
    cur.execute("alter table Employee add branch_name varchar(20) not null")  
except:  
    myconn.rollback()  
  
myconn.close()
  • 服務器端查看是否插入branch_name字段


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM