【问题标题】:how to insert variable into database with pyodbc?如何使用pyodbc将变量插入数据库?
【发布时间】:2018-04-09 07:13:02
【问题描述】:
highscore= score
cursor.execute("insert into tble values (hscore) hishscore.getvalue"):

que:分数将保存到可变的高分中。该高分需要保存到字段 hscore 的数据库中。插入和获取值的正确代码是什么。

【问题讨论】:

    标签: sql-server python-3.x pyodbc


    【解决方案1】:

    您想使用? 占位符绑定参数:

    cursor.execute("INSERT INTO tble (hscore) VALUES (?)", highscore)
    

    如果你想插入多个值,这里有一个更长的形式:

    cursor.execute(
        """
        INSERT INTO table_name
        (column_1, column_2, column_3)
        VALUES (?, ?, ?)
        """,
        (value_1, value_2, value_3)
    )
    

    您的VALUES 订单也不合适。祝你好运!

    【讨论】:

    • 不,我需要从变量中存储值。我可以解释一下……我的项目是一个 python 游戏。游戏结束后产生高分。这个高分值需要插入数据库。怎么可能?
    • 如果您将变量highscore 设置为值,那不是您要插入的吗?在示例中,它将向表tble 中插入一行,其中hscore 列的值是Python 变量highscore
    【解决方案2】:
    cursor.execute("insert into tablename(column1,column2) values (?,?);",var1,var2)
    

    我需要分号才能为我工作。

    【讨论】:

      【解决方案3】:

      假设列名是'hscore',要插入的变量是'highscore':

      cursor.execute("insert into tablename([hscore]) values(?)", highscore)
      

      【讨论】:

        【解决方案4】:
        you can follow the below code this is going write column values from csv , good example for your use case
        
        import pyodbc
        import io
        
        #credential file for server,database,username,password
        with io.open('cred.txt','r',encoding='utf-8')as f2:
            cred_data=f2.read()
            f2.close()
        cred_data=cred_data.split(',')
        server=cred_data[0]
        database=cred_data[1]
        username=cred_data[2]
        pwd=cred_data[3]
        
        
        
        con_obj=pyodbc.connect("DRIVER={SQL Server};SERVER="+server+";DATABASE="+database+";UID="+username+";PWD="+pwd)
        data_obj=con_obj.cursor()
        
        #data file with 5 columns
        with io.open('data.csv','r',encoding='utf-8')as f1:
            data=f1.read()
            f1.close()
        data=data.split('\n')[1:]
        i=1001
        for row in data:
            lines=row.split(',')
            emp=i
            fname=lines[0].split(' ')[0]
            sname=lines[0].split(' ')[1]
            com=lines[1]
            dep=lines[2]
            job=lines[3]
            email=lines[4]
            data_obj.execute("insert into dbo.EMP(EMPID,FNAME,SNAME,COMPANY,DEPARTMENT,JOB,EMAIL) values(?,?,?,?,?,?,?)", emp,fname,sname,com,dep,job,email)
            con_obj.commit()
            i=i+1
        

        【讨论】:

          猜你喜欢
          • 2018-12-21
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2012-07-09
          • 2017-03-16
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多