美文网首页
Python与Postgresql连接

Python与Postgresql连接

作者: DavidOcean | 来源:发表于2021-02-27 15:59 被阅读0次

    Postgresql数据有相较于其他数据库有自身的特点,通过Python与Postgresql数据库相连则是一项很不错的选择,通过Python来控制Postgresql的操作。

环境:

Python3.6.5

Postgresql 9.5

包:

psycopg2

核心代码:

conn = psycopg2.connect("postgresql数据库信息")   #针对postgresql创建连接,包含数据库名称,IP,用户名,密码,端口。

cur = conn.cursor()

cur.excute("sql语句")#需要执行的sql语句,包括增删查改的各项内容。

row = cur.fetchall()

cur.close()

conn.commit()

conn.close()

实例:

#创建一个sql控制的方法

def sql_add():

    try :

        conn = psycopg2.connect(("dbname='db1' host='10.10.10.10'"

                                    "user='postgres' password='mima'"))

    except :

        print("failed to connect")

    cur = conn.cursor()

    p = "北京幅"

    try :

        cur.execute(("INSERT INTO public.tab3(map_tfm) VALUES(%r)")%(p))

#      使用%来进行sql语句的拼接

        print("完成数据写入")

    except :

        print("数据写入失败")

    cur.close()

    conn.commit()

    conn.close()

相关文章

网友评论

      本文标题:Python与Postgresql连接

      本文链接:https://www.haomeiwen.com/subject/dbxmdctx.html