Inserting Data Using Connector/Python Example

本文通过Python代码演示了如何使用mysql.connector连接MySQL数据库,并创建了两个表:towns和hotels。随后,向这两个表中插入了若干条记录,并通过左连接查询了所有城镇及其关联的酒店信息。
摘要由CSDN通过智能技术生成

转自:http://www.wellho.net/resources/ex.php4?item=y115/py_mysql.py



import mysql.connector

conn = mysql.connector.Connect(host='192.168.200.115',user='demo',\
                        password='abc123',database='test')

c = conn.cursor()

c.execute("""drop table if exists towns""")
c.execute("""drop table if exists hotels""")

conn.commit()

c.execute("""create table towns (
        tid int primary key not NULL ,
        name text,
        postcode text)""")

c.execute("""create table hotels (
        hid int primary key not NULL ,
        tid int,
        name text,
        address text,
        rooms int,
        rate float)""")

c.execute("""insert into towns values (1, "Melksham", "SN12")""")
c.execute("""insert into towns values (2, "Cambridge", "CB1")""")
c.execute("""insert into towns values (3, "Foxkilo", "CB22")""")

c.execute("""insert into hotels values (1, 2, "Hamilkilo Hotel", "Chesterton Road", 15, 40.)""")
c.execute("""insert into hotels values (2, 2, "Arun Dell", "Chesterton Road", 60, 70.)""")
c.execute("""insert into hotels values (3, 2, "Crown Plaza", "Downing Street", 100, 105.)""")
c.execute("""insert into hotels values (4, 1, "Well House Manor", "Spa Road", 5, 80.)""")
c.execute("""insert into hotels values (5, 1, "Beechfield House", "The Main Road", 26, 110.)""")

conn.commit()

c.execute ("""select * from towns left join hotels on towns.tid = hotels.tid""")

for row in c:
        print (row)

c.close()

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值