python连接数据库
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 | import pymysql; #1.连接数据库 conn = pymysql.connect( host = 'localhost' , user = 'root' , password = '***' , #密码 db = 'jiang' , #数据库名 charset = 'utf8' , ) #2.创建游标对象 cur = conn.cursor() #3.对数据库进行CRUD操作 try : create_sqli = "create table hello (id int, name varchar(30));" cur.execute(create_sqli) except Exception as e: print ( "创建数据表失败:" , e) else : print ( "创建数据表成功;" ) # try : insert_sqli = "insert into hello values(1, '杨将');" cur.execute(insert_sqli) except Exception as e: print ( "插入数据失败:" , e) else : conn.commit() print ( "插入数据成功;" ) # 4. 关闭游标 cur.close() # 5. 关闭连接 conn.close() |
pyton连接数据库需要先安装pymysql模块:pip install pymysql
安装完成后导入pymysql模块:import pymysql
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】凌霞软件回馈社区,携手博客园推出1Panel与Halo联合会员
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步