python连接腾讯云数据库TDSQL-C(原CynosDB)

python连接腾讯云数据库TDSQL-C(原CynosDB)

一、连接步骤
1.安装 PyMySQL库
在这里插入图片描述
2.打开腾讯云TDSQL-C(原CynosDB)集群详情中的集群连接外网地址
在这里插入图片描述
3.代码部分,需要填写五个部分,其中host主机地址和port端口号就是第二步开启后显示的集群连接外网地址。类似以下格式“xxxxxxxxxxxxxxxxx.com:xxxxx”,冒号前面的是主机地址,后面的是端口号。账户密码.就是第三步的账户密码,延时是用的root账户。

代码如下:

import pymysql as mysql
######连接数据库
mydb = mysql.connect(
    host="sh-cynosdbmysql-grp-09q11w48.sql.tencentcdb.com",  # 数据库主机地址
    port=xxxxx,  # 端口号
    user="xxxx",  # 数据库用户名
    passwd="xxxx",  # 数据库密码
    database="xxxx"  # 选择一个数据库
)

mycursor = mydb.cursor()

######新建一个表######
try:
    mycursor.execute("CREATE TABLE sites (name VARCHAR(255), url VARCHAR(255))")
except:
    print("已经存在这个表了")

mycursor.execute("SHOW TABLES")
for x in mycursor:
    print(x)
'''主键设置'''
# mycursor.execute("ALTER TABLE sites ADD COLUMN id INT AUTO_INCREMENT PRIMARY KEY")

'''插入数据'''
sql = "INSERT INTO sites (name, url) VALUES (%s, %s)"
val = ("RUNOOB", "https://www.runoob.com")
mycursor.execute(sql, val)
mydb.commit()  # 数据表内容有更新,必须使用到该语句
print(mycursor.rowcount, "记录插入成功。",mycursor.lastrowid)

'''批量插入'''
sql = "INSERT INTO sites (name, url) VALUES (%s, %s)"
val = [
    ('Google', 'https://www.google.com'),
    ('Github', 'https://www.github.com'),
    ('Taobao', 'https://www.taobao.com'),
    ('stackoverflow', 'https://www.stackoverflow.com/')
]

mycursor.executemany(sql, val)

mydb.commit()  # 数据表内容有更新,必须使用到该语句

print(mycursor.rowcount, "记录插入成功。",mycursor.lastrowid)



mycursor.execute("SELECT * FROM sites")

myresult = mycursor.fetchall()  # fetchall() 获取所有记录
for x in myresult:
    print(x)

'''读取指定的字段数据'''
mycursor.execute("SELECT name, url FROM sites")
myresult = mycursor.fetchall()

for x in myresult:
    print(x)

'''删除记录'''
sql = "DELETE FROM sites WHERE name = 'stackoverflow'"
mycursor.execute(sql)
mydb.commit()
print(mycursor.rowcount, " 条记录删除")

猜你喜欢

转载自blog.csdn.net/weixin_44925547/article/details/114315474