|
|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
给数据库插入数据,在 init 里明明 定义了 conn 和 cursor ,但是执行程序还是报错,报DB 里面没有属性conn 或者是 corsor。
不知道是哪里的问题。。。
数据库我单独用简单的测试方法试了,是可以连接上的。
- class DB:
- def __init__self(self):
- try:
- # =====连接数据库
- self.conn = pymysql.connect(host=db_host, port=db_port, user=db_username, password=db_password, db=db_name,
- charset='utf-8',
- cursorclass=pymysql.cursors.DictCursor)
- self.cursor = self.conn.cursor()
- except OperationalError as e:
- print('mysql Error %d: %s' % (e.args[0], e.args[1]))
- # 清除表数据
- def clear(self, table_name):
- real_sql = 'delete from' + table_name + ';'
- with self.conn.cursor() as cursor:
- cursor.execute('SET FOREIGN_KEY_CHECKS = 0;')
- cursor.excute(real_sql)
- self.conn.commit()
- # 插入表数据
- def insert(self, table_name, table_data):
- for key in table_data:
- table_data[key] = "'"+str(table_data[key])+"'"
- key = ','.join(table_data.keys())
- value = ','.join(table_data.values())
- real_sql = 'INSERT INTO' + table_name + '('+key+') VALUES('+value+')'
- #print(real_sql)
- #with self.conn.cursor() as cursor:
- self.cursor.execute(real_sql)
- self.conn.commit()
- # 关闭数据库连接
- def close(self):
- self.conn.close()
- if __name__ == '__main__':
- db = DB()
- table_name = 'f_course'
- data = {'course_name': 'test课程一',
- 'course_price': 9900,
- 'on_sale': 0,
- 'course_state': 1,
- 'free': 0,
- 'state': 0,
- 'teacher_id': 1,
- 'create_time': '2019-02-10 00:25:42'
- }
- # db.clear(table_name)
- db.insert(table_name, data)
- db.close()
复制代码
============
可以连接数据的代码- import pymysql
- conn = pymysql.Connect(host='121.42.203.***', port=3306, user='admin', passwd='6216', db='test')
- cur = conn.cursor()
- cur.execute("select version()")
- sql2 = 'SELECT * FROM f_course'
- cur.execute(sql2)
- for i in cur:
- print(i)
- cur.close()
- conn.close()
复制代码 |
-
|