利用python 连接数据库
import pymysql import pandas as pd
In [4]:
conn=pymysql.Connect("192.168.1.8","root","Password","mysqljingjie",charset="utf8")
conn #建立连接,连接之后打印conn'查看是否连接成功
Out[4]:
注:在初次连接数据库时失败,显示1061错误,判定是数据库没有连接权限导致的,在mysql本机进行如下操作后,重启mysql服务,连接成功
如果想让192.168.10.83能够连接到本地的这个数据库,要让数据库给其分配权限,登录mysql,执行:(username 和 password是登录mysql的用户名和密码)
GRANT ALL PRIVILEGES ON . TO '账户名'@'192.168.10.83' IDENTIFIED BY 'password' WITH GRANT OPTION;
如果要想所有的外部ip地址都能够访问使用mysql,可以执行下面: GRANT ALL PRIVILEGES ON . TO '账户名'@'%' IDENTIFIED BY 'password' WITH GRANT OPTION;
In [5]:
cur=conn.cursor()#创建游标
In [6]:
cur.execute("select*from employee")#执行sql语句
Out[6]:
In [7]:
#cur.fetchone()#返回一条结果 #cur.fetchmany()#返回指定条数 ser=cur.fetchall()#返回所有元组
In [8]:
columnDes = cur.description#获取描述信息
In [11]:
columnNames = [columnDes[i][0] for i in range(len(columnDes))]#获取列名称 df = pd.DataFrame([list(i) for i in ser],columns=columnNames) df
Out[11]:
In [136]:
conn.close()#关闭连接,否者浪费资源
插入新内容
In [123]:
#sql="""insert into bank(b_id,bank_name) ,values("B0005","成都银行")"""
In [126]:
conn=pymysql.Connect("192.168.1.8","root","password","mysqljingjie",charset="utf8") cur=conn.cursor() cur.execute(sql) conn.commit()#提交事务 # 发生错误时回滚 conn.rollback() conn.close()
In [127]:
ser
Out[127]:
In [120]:
def get_df_from_db(sql): cursor = connection.cursor() cursor.execute(sql) data = cursor.fetchall() columnDes = cursor.description #获取连接对象的描述信息 columnNames = [columnDes[i][0] for i in range(len(columnDes))] df = pd.DataFrame([list(i) for i in data],columns=columnNames) return df
In [113]:
import pandas as pd
In [ ]:
description()
In [16]:
len(columnDes)
Out[16]:
In [17]:
columnDes
Out[17]: