美文网首页工作日志
数据库代码 python

数据库代码 python

作者: 啊哈JC熙 | 来源:发表于2018-05-29 16:58 被阅读8次
    
    # 新建数据库 存储iris数据
    CREATE DATABASE `Iris_Data`;
    
    USE `Iris_data`;
    
    #iris 表格
    CREATE TABLE `iris`(
        `sepal length` int,
        `sepal width` int,Iris_Data
        `petal length` int,
        `petal width` int,
        `target` VARCHAR(100) 
    );
    
    DROP TABLE `iris`;
    
    CREATE TABLE `iris`(
        `sepal_length` FLOAT NULL,
        `sepal_width` FLOAT NULL,
        `petal_length` FLOAT NULL,
        `petal_width` FLOAT NULL,
        `target` VARCHAR(100) NULL
    );
    
    INSERT INTO `iris`(`sepal_length`,`sepal_width`,`petal_length`,`petal_width`,`target`) VALUE (5.1,3.5,1.4,0.2,"setosa");
    
    

    python 插入数据库代码

    # -- coding: utf-8 --
    import MySQLdb
    import pandas as pd
    
    #将获取链接封装成calss
    class MysqlSearch(object):  # 让MysqlSearch类继承object对象
    
        def __init__(self): # 在初始化的时候调用
            self.get_conn()
    
    
        def get_conn(self): # 数据库链接
            try:
                self.conn = MySQLdb.connect(
                    host = "127.0.0.1",
                    user = "root",
                    passwd = "mysql123",
                    db = "Iris_Data",
                    port = 3306,
                    charset = 'utf8'
                    )
            except Exception as e:
                print("Error : %s" % e)
    
        def close_conn(self):   #关闭数据库
            try:
                if self.conn:
                    # 关闭链接
                    self.conn.close()
            except Exception as e:
                print("Error: %s" % e)
    
        def add_one(self,sepal_length, sepal_width, petal_length, petal_width, target):
            """事务处理"""
            try:
                # 准备SQL
                sql =(
                    "INSERT INTO `iris` VALUE ( %s, %s, %s, %s, %s );"
                )
                # 出现换行的时候用一个元组扩起来。 应用双引号扩起来
                # 获取链接和cursor
                cursor = self.conn.cursor()
                # 执行SQL
                cursor.execute(sql, (sepal_length, sepal_width, petal_length, petal_width, target))
                # 错误
                # 提交数据到数据库
                """ 如果不提交的事务的话。就是 已经提交多数据库 但是没有被保存  """
                # 提交事务
                self.conn.commit()
                # 关闭cursor
                cursor.close()
            except :
                print("Error")
                # self.conn.commit() # 部分提交
                self.conn.rollback() # 回滚
            # 关闭链接
            self.close_conn()
    
        def add_more(self):
            try:
                sql =(
                    "INSERT INTO `iris` VALUE ( %s, %s, %s, %s, %s );"
                )
                cursor = self.conn.cursor()
                df =  pd.DataFrame(pd.read_csv('iris.csv',header=None))
    
                for index in df.index:
                    sepal_length = df.loc[index].values[0]
                    sepal_width = df.loc[index].values[1]
                    petal_length = df.loc[index].values[2]
                    petal_width = df.loc[index].values[3]
                    target = df.loc[index].values[4]
                    print(sepal_length, sepal_width, petal_length, petal_width, target)
                    cursor.execute(sql, (sepal_length, sepal_width, petal_length, petal_width, target))
                self.conn.commit()
                cursor.close()
                
            except :
                print("Error")
                self.conn.rollback()
            self.close_conn()
            pass    
    
    def main():
        obj = MysqlSearch()
        obj.add_more()
        print("************************** Finish **************************")
    
    if __name__ == '__main__':
        main()
       
    

    存储工程学习

    1.1python大文件分块下载,文件分块1024=1M

    import requests
    file_url = "http://aima.cs.berkeley.edu/data/iris.csv" # iris数据集下载地址
    request_file =  requests.get(file_url, stream=True)
    with open("iris.csv", "wb") as iris:
        for chunk in request_file.iter_content(chunk_size=1024):
            if chunk:
                iris.write(chunk)
    

    1.2 pandas读数据

    import pandas as pd
    df =  pd.DataFrame(pd.read_csv('iris.csv',header=None))  # 无表头
    df.info()
    a = df.shape
    df.head()
    

    相关文章

      网友评论

        本文标题:数据库代码 python

        本文链接:https://www.haomeiwen.com/subject/ogyajftx.html