【问题标题】:Get data from SQL Result从 SQL 结果中获取数据
【发布时间】:2017-07-19 22:27:04
【问题描述】:

有人可以帮我理解如何选择在 sql RESULT 中显示的字段值吗?我想使用该值来运行新的不同查询。

我正在使用 Python 连接 html、apache 和 sql server 来创建一个将运行 SQL 查询并显示结果的网站。一旦我得到结果,我想在新的 SQL 查询中使用一列的值。有没有办法做到这一点,而不是在表单中手动输入值?

代码 1:下面的代码执行数据库调用,根据 sql 查询显示结果。

# prepare a cursor object using cursor() method
cursor = db1.cursor()

SQLQuery = ("SELECT  I.OpinionID,
                     I.TimeStamp,
                     I.Strategy,
                     I.ExpectedTradingPrice,
                     I.ExpectedDate,
                     I.CPAMAnalyst,
                     I.Conviction,
                     I.Status,
                     N.DebtTicker,
                     N.InstrumentType,
                     N.ExpectedMaturity,
                     N.OrderSize,
                     N.Allocation
                 From [CpamTestAugustTestSteve].[dbo].[NewIssueOpinion] I
                 INNER JOIN [CpamTestAugustTestSteve].[dbo].[NewIssue] N ON I.NewIssueID = N.NewIssueID
                 WHERE N.ExpectedIssueDate >= GetDate()-30
                     AND I.Status = 'Suggested' AND I.Active = 1;")

#Execute the SQL command
cursor.execute(SQLQuery)


#Fetch all the rows in a list of lists.
results=cursor.fetchall()
y = len(results)


print "<br> <br>"
print "<body2>"
print """<form action="http://localhost/NewIssueStatusUpdate.py" method="post">
            <div> <input type="Submit" class= "submitbutton" value="Submit" /> </div> <br> <br>
</form>"""
if  not cursor.rowcount:
    print "<b> <mark> NO RECORDS FOUND!!</mark> </b>"
else:
    print "<TABLE>"
    print "<tablebody>"
    print"<tr>"
    print "<tr><th>S.No</th><th>OpinionID</th> <th>TimeStamp</th> <th>Strategy</th> <th>ExpectedTradingPrice</th> <th>ExpectedDate</th> <th>CPAMAnalyst</th> <th>Conviction</th> <th>Status</th> <th>DebtTicker</th> <th>InstrumentType</th> <th>ExpectedMaturity</th> <th>OrderSize</th> <th>Allocation</th><th>New Status</th>"
    for p in range(y):
        print "<tr><td>%s</td>" %(p+1)
        for q in range(len(results[p])):
            r= results[p][q]   
            print "<td> %s </td>" % (r)
    print "<td><select id='statusSelect' onchange='myChangeHandler(this)'><option value='Suggested'>Select</option><option value='accept'>Accept</option><option value='reject'>Reject</option><option value='terminated'>Terminated</option></select></td>"
    print "</TABLE>"
    from tabulate import tabulate

我在“新状态”上方的结果中添加了一个自定义列,我们可以在其中选择要分配给记录的新状态。

我想写一个可以用来更新数据库的代码。查询是:

"UPDATE NewIssueOpinion " & _
"SET Status = '" & Status & "' " & _ #Getting Status using getformvalue.
"WHERE OpinionID = " & OpinionID & ";"     #How can we select the Opinion ID value from the result displayed from code1.

更新代码:

# prepare a cursor object using cursor() method
cursor = db1.cursor()

SQLQuery = ("SELECT  I.OpinionID,
                     I.TimeStamp,
                     I.Strategy,
                     I.ExpectedTradingPrice,
                     I.ExpectedDate,
                     I.CPAMAnalyst,
                     I.Conviction,
                     I.Status,
                     N.DebtTicker,
                     N.InstrumentType,
                     N.ExpectedMaturity,
                     N.OrderSize,
                     N.Allocation
                 From [CpamTestAugustTestSteve].[dbo].[NewIssueOpinion] I
                 INNER JOIN [CpamTestAugustTestSteve].[dbo].[NewIssue] N ON I.NewIssueID = N.NewIssueID
                 WHERE N.ExpectedIssueDate >= GetDate()-30
                     AND I.Status = 'Suggested' AND I.Active = 1;")

#Execute the SQL command
cursor.execute(SQLQuery)


#Fetch all the rows in a list of lists.
results=cursor.fetchall()
y = len(results)
#define function
def Review():
    cursor.close()
    cursor = db1.cursor()
    for result in results: 
        my_OpinionID = result[1] 
        my_StatusID = result[14] 
        cursor.execute('UPDATE [CpamTestAugustTestSteve].[dbo].[NewIssueOpinion] SET Status = ? WHERE OpinionID = ?', (my_StatusID, my_OpinionID))
        db1.commit()
        cursor.close()
        db1.close()    
location.reload()
print "<br> <br>"
print "<body2>"
print "<form method='post' onclick='return Review();'>"
print "<div> <input type='Submit' class= 'submitbutton' value='Submit' /> </div> <br> <br>"
print "</form>"
if  not cursor.rowcount:
    print "<b> <mark> NO RECORDS FOUND!!</mark> </b>"
else:
    print "<TABLE>"
    print "<tablebody>"
    print"<tr>"
    print "<tr><th>S.No</th><th>OpinionID</th> <th>TimeStamp</th> <th>Strategy</th> <th>ExpectedTradingPrice</th> <th>ExpectedDate</th> <th>CPAMAnalyst</th> <th>Conviction</th> <th>Status</th> <th>DebtTicker</th> <th>InstrumentType</th> <th>ExpectedMaturity</th> <th>OrderSize</th> <th>Allocation</th><th>New Status</th>"
    for p in range(y):
        print "<tr><td>%s</td>" %(p+1)
        for q in range(len(results[p])):
            r= results[p][q]   
            print "<td> %s </td>" % (r)
    print "<td><select id='statusSelect'><option value='Suggested'>Select</option><option value='Accepted'>Accept</option><option value='rejected'>Reject</option><option value='terminated'>Terminated</option></select></td>"
    print "</TABLE>"
    from tabulate import tabulate                    
print "</body2>"


db1.commit()

当我单击提交按钮时,页面正在重新加载,但数据库没有更新。不知道出了什么问题!

【问题讨论】:

  • 嗨,艾迪。我知道你会发现这里有很多人喜欢帮助其他处于困境的人,但都懒得为你写一个完整的程序。如果您通过添加您目前使用的代码以及有问题或缺失的部分来编辑您的帖子,它可能会有所不同(并且反对票将停止)
  • 非常感谢 Ettore,:) 我已更新问题以添加代码。我非常感谢您的回复,以帮助我获得更好的帮助/回复。我也是 Stackoverflow 的新手。到目前为止,我只用它来研究现有问题,最近我开始提出问题。仍在想办法做到这一点。
  • 读者确实想在这里提供帮助,但是对于社区的新手来说显然不能成为乞求志愿者免费工作的借口。明白某事只对发帖人来说是紧急的,而对其他人根本没有,这一点很重要。
  • 谢谢哈弗。不知道知识共享请求如何被解释为乞讨!!
  • 我赞成答案,但似乎我需要 15+ 的声誉才能显示我的投票。他们正在存储我的反馈但没有显示。我正在尝试我在这里得到的所有答案,但我的代码仍然没有工作。可能是缺少了什么。我会根据输入不断更新我的代码。

标签: python html css sql-server


【解决方案1】:

对于 cursor.execute(SQLQuery, multi=True) 中的结果: if result.with_rows:

同样,上次我尝试连接到数据库并打印我使用的结果

【讨论】:

    【解决方案2】:

    这里有 2 分:

    cur.fetchall 返回一个元组的元组。 results[0][0] 将是查询返回的数据中第一行的 OpinionIDresults[1][0] 将是第二行的 OpinionID,以此类推。results [0][7] 将是第一行的 Status,以此类推。

    不要使用 Python 的字符串连接构建查询。使用安全的方法。

    my_first_OpinionID = results[0][0]
    my_first_statusID = results[0][7]  
    cur.execute("UPDATE NewIssueOpinion SET Status = ? WHERE OpinonID = ?", (my_first_OpinionID, my_first_statusID))
    

    您可能会发现这些链接很有用:

    <http://zetcode.com/db/mysqlpython/>  
    <http://bobby-tables.com/python>  
    <http://sebastianraschka.com/Articles/2014_sqlite_in_python_tutorial.html>
    

    【讨论】:

    • 我相信,代码只会读取第一行中的意见 ID 和状态 ID,我希望能够对所有显示为结果的行执行此操作。
    • 您通常如何阅读元组或列表? with result in results: my_OpinionID = result[0], my_StatusID[7] 等。在我的回答中,第一个索引是,第二个索引是行中的位置
    • P.S.更新时不要忘记提交事务!
    • 我了解,但数据是动态的。结果中的行数不固定。在这种情况下应该怎么做?
    • 2 种方式。 (1) 循环! for result in results: my_OpinionID = result[0], my_StatusID = result[7], cur.execute("cur.execute("UPDATE NewIssueOpinion SET Status = ? WHERE OpinonID = ?", (my_OpinionID, my_statusID))") 和 (2) executemany - 看到我提供的链接,他们比我更好地解释了如何使用 executemany(但值得一读,因为它比循环更有效)
    猜你喜欢
    • 2018-05-16
    • 2023-03-21
    • 2015-11-09
    • 2017-09-30
    • 2010-09-27
    • 2014-11-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多