利用Python进行postgres、mysql数据库基本操作(建表、插入数据、删除数据、添加字段注释)

11 篇文章 0 订阅
1 篇文章 0 订阅

一、 postgres数据库基本操作

共有建表、插入数据、、查询数据、删除数据、添加字段注释等5种操作,分为4步

import psycopg2

#step1
conn=psycopg2.connect(database='gndsj',user='postgres',password='postgres',host='172.0.0.88',port='5432')
cursor=conn.cursor()

#step2
## 建表
cursor.execute("CREATE TABLE test_conn(id int, name text)")

#插入数据
cursor.execute("INSERT INTO test_conn values(1,'haha')")

查询数据
cursor.execute("select * from test_conn")

删除表
cursor.execute("DROP TABLE test_conn")

#添加字段注释
cursor.execute("comment on column test_conn.id is 'ID'; )

#step3
## 提交SQL命令
conn.commit()

#step4
## 关闭游标
cursor.close()
## 关闭数据库连接
conn.close()

二、 MYSQL进行建表、插入数据操作

mysql建表和插入数据操作

import pymysql

# pymysql.install_as_MySQLdb()
db = pymysql.connect(host="localhost",user="root",password="123456",db="mydatabase",port=3306 )
cursor=db.cursor()

#建表
cursor.execute("CREATE TABLE test_conn(id int, name text)")

#插入数据
cursor.execute("insert into test_conn(id, name) values('1','装神弄鬼')")   

db.commit()  

cursor.close()
db.close()

以上为简单的基础知识,postgres和mysql之间存在两点区别:1、使用的包不一样,2、数据插入语句不一样,熟悉postgres和mysql数据库基本语法基本可以满足使用要求。

实际使用来批量建表、插入数据、添加表和字段注释操作在下一篇文章再写。

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值