在python3.4版本中不支持python2.X中的MySQLdb,需要导入pymysql包,不要安装错了。
1、CMD下输入pip install pymysql 导入pymysql包
2、测试代码如下:
实现查询功能:
import pymysql try: #获取数据库连接 conn=pymysql.connect(host='localhost',user='root',password='root',db='pythonDB',port=3306,charset='utf8') cur=conn.cursor()#获取一个游标 cur.execute('select * from test') data=cur.fetchall() #遍历输出 for d in data:# print("ID:"+str(d[0])+' name:'+str(d[1])) cur.close()#释放游标 conn.close()#释放资源 except Exception as e: print("异常"+e)
运行结果:
ID:1 name:tom
ID:2 name:张三
ID:3 name:李四
实现插入功能:
import pymysql name = 'abc' author = 'abcdg' keyword = 'hyrhy' coden = 'rhgji' try: # 获取数据库连接 conn = pymysql.connect(host='localhost', user='root', password='root', db='pythonDB', port=3306, charset='utf8') cur = conn.cursor() # 获取一个游标 sql=" INSERT INTO library ( t_name , t_automer , t_keyword , t_coden ) VALUES (%s,%s,%s,%s );" print(sql) cur.execute(sql,( name , author , keyword , coden ))#加载sql语句 conn.commit()#提交事务 cur.close() # 释放游标 conn.close() # 释放资源 except Exception as e: print("异常" + e)
注: 表名最好是设置为t_****的格式,要不然容易出现Youhave an error in your SQL syntax; check the manual that
corresponds to your MySQL server versionfor the right syntax to use near .......
表示不止一次掉进这个坑了