使用python和mysql.conn

2024-04-23 11:21:54 发布

您现在位置:Python中文网/ 问答频道 /正文

我用的是“Python3.4”和Mysql.connector“用于连接数据库。和访问Xampp Mysql,在本地主机上运行代码。 下面给出的代码是我用来连接数据库和获取数据的代码

  #!"C:\python34\python.exe"
    import sys
    import mysql.connector
    print("Content-Type: text/html;charset=utf-8")
    print()

    /* code to connect datbase*/
    conn = mysql.connector.connect(host='localhost',port='8051',
                                           database='test',
                                           user='root',
                                           password='Tom')
    cursor = conn.cursor()                                 
    if conn.is_connected():
        print('sucessfull...Connected to MySQL database')
    cursor.execute(" SELECT * FROM testtable1 ")
print ("<html>")
print("<p>")
print("hai")
print("</p>")
print("<body")
print ("<table border='2'>")
print ("<tr><td>")


for row in cursor.fetchall():
        print (row)
print ("</td></tr>")
print  ("</table>")
print ("</body>")
print ("</html>")

输出如下: 成功…已连接到MySQL数据库

我不能显示表内的数据,没有表也无法打印从表中获取的数据。 在localhost中以http://localhost:804/cgi-bin/test.py身份运行代码 是因为xampp或apache造成的任何问题。 请给点建议


Tags: to代码testimport数据库localhostconnectorhtml