怎么用python连接数据库_python连接pg数据库

大家好,又见面了,我是你们的朋友全栈君。

实现步骤:
一、使用mysql.connector
1、导入msql 的包
2、创建连接对象
3、使用cursor方法获取操作游标
4、fetchall方法获取数据,for循环进行输出
5、最后关闭连接对象

<code style="margin-left:0">import <a href="https://www.mhzhuji.com/kwck/57"  class="lar_link lar_link_outgoing" data-linkid="219" data-postid="549"  title="数据库MySQL"  rel="nofollow" target="_blank" >mysql</a>.connector
#创建连接对象
#参数分别为:ip地址,用户名,密码,库名
mydb=<a href="https://www.mhzhuji.com/kwck/57"  class="lar_link lar_link_outgoing" data-linkid="219" data-postid="549"  title="数据库MySQL"  rel="nofollow" target="_blank" >mysql</a>.connector.connector(
    host="192.168.139.128",
    user="root",
    passwd="root",
    database="shops"
)

#使用cursor方法获取操作游标
cursor = mydb.cursor()

#使用execute方法执行一条sql语句
cursor.execute("select * from xxxtable")

#使用ferchall获取数据
data=cursor.fetchall()
for x in data:
    print(x)
mydb.close
实现数据的插入

sql=""" insert into test(name,age) values("xxxname",23)"""
test = mydb.cursor()
test.execute(sql)#执行sql语句</code>

二、pyMysql连接数据库

<code style="margin-left:0">import  pymysql

#参数分别为:ip,用户名,密码,库名
db=pymysql.connect("192.168.139.128","root","root","shops")
cursor=db.cursor()
cursor.execute("select * from goods limit 3")
result=cursor.fetchall()
for x in result:
    print(x)</code>

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

发布者:全栈程序员栈长,转载请注明出处:https://javaforall.cn/204013.html原文链接:https://javaforall.cn

未经允许不得转载:木盒主机 » 怎么用python连接数据库_python连接pg数据库

赞 (0)

相关推荐

    暂无内容!