在本教程的这一部分中,我们将创建名为 Employee 的新表格。在建立连接对象时,我们必须提到数据库名称。

我们可以使用 SQL 的 CREATE TABLE 语句来创建新表格。在我们的 PythonDB 数据库中,表格 Employee 最初将具有四列,即 name、id、salary 和 department_id。

以下查询用于创建新表格 Employee。

>  create table Employee (name varchar(20) not null, id int primary key, salary float not null, Dept_Id int not null)  

示例

import mysql.connector  
  
#Create the connection object   
myconn = mysql.connector.connect(host = "localhost", user = "root",passwd = "google",database = "PythonDB")  
  
#creating the cursor object  
cur = myconn.cursor()  
  
try:  
    #Creating a table with name Employee having four columns i.e., name, id, salary, and department id  
    dbs = 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()  

77-1.png

现在,我们可以检查表格 Employee 是否存在于数据库中。

修改表格

有时,我们可能会忘记创建一些列,或者需要更新表格架构。如果需要,可以使用 alter 语句来修改表格架构。在这里,我们将向表格 Employee 添加一个名为 branch_name 的列。以下 SQL 查询用于此目的。

alter table Employee add branch_name varchar(20) not null  

考虑以下示例。

示例

import mysql.connector  
  
#Create the connection object   
myconn = mysql.connector.connect(host = "localhost", user = "root",passwd = "google",database = "PythonDB")  
  
#creating the cursor object  
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()  

77-2.png

标签: Tkinter教程, Tkinter安装, Tkinter库, Tkinter入门, Tkinter学习, Tkinter入门教程, Tkinter, Tkinter进阶, Tkinter指南, Tkinter学习指南, Tkinter进阶教程, Tkinter编程