MySQL-基础操作

创建数据库

语句-CREATE DATABASE name
# 安装pymysql pip3 install PyMySQL
# 连接MySQL
import pymysql
mydb = pymysql.connect(
    "localhost",
    "root",
    '123456',
)
mycursor = mydb.cursor()
mycursor.execute('CREATE DATABASE test_hong_3')

mydb.close()

使用数据库

语句-USE name

创建表

语句-CREATE TABLE name(键 数据类型 约束条件,键 数据类型)
# 安装pymysql pip3 install PyMySQL
# 连接MySQL
import pymysql
mydb = pymysql.connect(
    "localhost",
    "root",
    '123456',
)
mycursor = mydb.cursor()
mycursor.execute("USE test_hong_3")
SQL = "CREATE TABLE my_test (id CHAR(20) NOT NULL,name CHAR(20))"

try:
    mycursor.execute(SQL)
    mydb.commit()
except:
    mydb.rollback()
mydb.close()
结果:
新建表结构.png

插入数据

语句-INSERT INTO table_name(键,键) VALUES(值,值)
# 安装pymysql pip3 install PyMySQL
# 连接MySQL
import pymysql
mydb = pymysql.connect(
    "localhost",
    "root",
    '123456',
)
mycursor = mydb.cursor()
mycursor.execute("USE test_hong_3")
insert = "INSERT INTO my_test(id,name) VALUES('12345','oliva')"

try:
    mycursor.execute(insert)
    mydb.commit()
except:
    mydb.rollback()
mydb.close()

结果:
表中插入数据.png

删除表中记录

语句-DELETE FROM table_name [匹配条件]
# 安装pymysql pip3 install PyMySQL
# 连接MySQL
import pymysql
mydb = pymysql.connect(
    "localhost",
    "root",
    '123456',
)
mycursor = mydb.cursor()
mycursor.execute("USE test_hong_3")

delete = "DELETE FROM my_test WHERE id='6789'"
try:
    mycursor.execute(delete)
    mydb.commit()
except:
    mydb.rollback()
mydb.close()

结果:
再次添加一条数据.png

删除后的数据.png

更新表中记录

语句-UPDATE table_name SET 键=值 约束条件
# 安装pymysql pip3 install PyMySQL
# 连接MySQL
import pymysql
mydb = pymysql.connect(
    "localhost",
    "root",
    '123456',
    'test_hong_3'
)
mycursor = mydb.cursor()

update = "UPDATE my_test SET name='update_oliva' WHERE id='12345'"
try:
    mycursor.execute(update)
    mydb.commit()
except:
    mydb.rollback()
mydb.close()
结果:
更新记录.png

获取查询数据

# 安装pymysql pip3 install PyMySQL
# 连接MySQL
import pymysql
mydb = pymysql.connect(
    "localhost",
    "root",
    '123456',
    'test_hong_3'
)
mycursor = mydb.cursor()

select= "SELECT * FROM  my_test"

try:
    mycursor.execute(select)
    mydb.commit()
except:
    mydb.rollback()
data = mycursor.fetchall()
print('数据',data[0])
mydb.close()
结果:
查询到数据.png

删除表

语句-DROP TABLE table_name
# 安装pymysql pip3 install PyMySQL
# 连接MySQL
import pymysql
mydb = pymysql.connect(
    "localhost",
    "root",
    '123456',
    'test_hong_3'
)
mycursor = mydb.cursor()

drop = "DROP TABLE test_table"

try:
    mycursor.execute(drop)
    mydb.commit()
except:
    mydb.rollback()
# data = mycursor.fetchall()
# print('data',data[0])
mydb.close()
结果:
新建表.png

删除整表.png

你可能感兴趣的:(MySQL-基础操作)