1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40
| import pymysql
# 1. 连接 MySQL的某数据库 conn = pymysql.connect( host="127.0.0.1", # 使用本地主机 port=62201, # MySQL 的映射端口 user='your_username_mysql', # 用户名 password='your_password_mysql', # 密码 charset='utf8', database='your_database_name_mysql' # 数据库名 ) cursor = conn.cursor()
# 2. 创建表 create_table_query = ''' CREATE TABLE IF NOT EXISTS my_sheet ( id INT AUTO_INCREMENT PRIMARY KEY, username VARCHAR(50) NOT NULL, password VARCHAR(50) NOT NULL, mobile VARCHAR(15) NOT NULL ); '''
cursor.execute(create_table_query) print("表创建成功或已存在!")
# drop_table_query = "DROP TABLE IF EXISTS my_sheet;" # cursor.execute(drop_table_query) # 删除表
# 3. 插入数据 insert_query = "INSERT INTO my_sheet (username, password, mobile) VALUES (%s, %s, %s)" cursor.execute(insert_query, ('xiaoliu', 'qwe123', '15155555555')) conn.commit() print("数据插入成功!")
cursor.close() conn.close()
|