如何从在线(托管)mysql数据库访问和编辑数据

问题描述 投票:0回答:2

我当时正在创建一个类似程序的小型聊天室,用户可以在其中注册,登录,发送和接收消息(在Pycharm中)。该程序在mysql数据库中包含用户详细信息,并在txt文件中聊天我想在线托管它,以便可以由不同的用户在不同的计算机上访问它,所以我必须对我的代码进行哪些更改(当前设计为在单台计算机上工作)

import pymysql
import random
def register(firstName,lastName,password,userName,emailId):
    db = pymysql.connect("localhost","root","pass","USERS")
    cursor = db.cursor()
    r=1
    while(r!=0):
        id = chr(random.randrange(65, 91)) + str(random.randrange(0, 10)) +str(random.randrange(0, 10))
        r = cursor.execute("SELECT * FROM UserData WHERE ID = '{}';".format(id))


    sql = "INSERT INTO UserData VALUES('{}','{}','{}','{}','{}','{}');".format(id,firstName,lastName,password,userName,emailId)
    try:
        cursor.execute(sql)
        print("Registration successful")
        file = open(id+'N.txt', 'a')
        db.commit()
    except Exception as e:
        print("Registration unsuccessful")
        print(str(e))
        db.rollback()
    db.close();


def displayNew(userId):
    file = open(userId+'N.txt', 'r')
    for message in file:
        print(message)
    open(userId+'N.txt', 'w').close()

def sendMessage(sender):
    receiver = input("RECEIVER's USERNAME : ")
    r = cursor.execute("SELECT * FROM UserData WHERE UserName = '{}';".format(receiver))
    if (r == 1):
        userInfo = cursor.fetchone()
        if(sender>userInfo[0]):
            chatfile = open(sender+'&'+userInfo[0]+'.txt', 'a')
        elif(sender<userInfo[0]):
            chatfile = open(userInfo[0]+'&'+sender+'.txt', 'a')
        newfile=open(userInfo[0]+'N.txt', 'a')
        message = input("MESSAGE(Single Line): ")
        cursor.execute("SELECT * FROM UserData WHERE ID = '{}';".format(sender))
        senderInfo = cursor.fetchone()
        senderName = senderInfo[4]
        chatfile.write(senderName+": "+message+"\n")
        newfile.write(senderName+": "+message+"\n")
    else:
        print("USER DOES NOT EXIST")
        retry=input("WANT TO RETRY(y/n)")
        if(retry=="y"):
            sendMessage(sender)

def oldMessage(receiver):
    sender = input("SENDER's USERNAME : ")
    r = cursor.execute("SELECT * FROM UserData WHERE UserName = '{}';".format(sender))
    if (r == 1):
        userInfo = cursor.fetchone()
        if(receiver>userInfo[0]):
            chatfile = open(receiver+'&'+userInfo[0]+'.txt', 'r')
        elif(receiver<userInfo[0]):
            chatfile = open(userInfo[0]+'&'+receiver+'.txt', 'r')
        for message in chatfile:
            print(message)

    else:
        print("USER DOES NOT EXIST")
        retry=input("WANT TO RETRY(y/n)")
        if(retry=="y"):
            sendMessage(sender)



while(True):
    db = pymysql.connect("localhost", "root", "dineshrashmi", "USERS")
    cursor = db.cursor()
    print("CHOICE 1: Login")
    print("CHOICE 2: Register")
    print("CHOICE 3: Exit")
    ch = int(input("Enter Your Choice : "))

    if(ch==1):
        userName = input("User Name : ")
        r=cursor.execute("SELECT * FROM UserData WHERE UserName = '{}';".format(userName))
        if(r==1):
            userInfo = cursor.fetchone()
            password = input("Password : ")
            if(userInfo[3]==password):
                cursor.execute("SELECT * FROM UserData WHERE UserName = '{}';".format(userName))
                print("WELCOME "+userInfo[1].upper()+" "+userInfo[2].upper())
                displayNew(userInfo[0])
                send=input("Do You Want To Send A Message(y/n) : ")
                if(send=="y"):
                    sendMessage(userInfo[0])
                view = input("Do You Want To View Old Message(y/n) : ")
                if (view == "y"):
                    oldMessage(userInfo[0])
                break
            else:
                print("INVALID PASSWORD")
        else:
            print("USER DOES NOT EXIST")
        print("\n")



    elif(ch==2):
        confirmPass = False
        userNameDuplicate = 1
        emailDuplicate = 1
        firstName = input("First Name : ")
        lastName = input("Last Name : ")

        while(userNameDuplicate!=0):
            userName = input("User Name : ")
            userNameDuplicate = int(cursor.execute("SELECT * FROM UserData WHERE UserName = '{}';".format(userName)))
            if (userNameDuplicate != 0):
                print("USER NAME ALREADY TAKEN")
                print("Try Again!")

        while(not confirmPass):
            password = input("Password : ")
            cpassword = input("Confirm Password : ")
            if(password==cpassword):
                confirmPass = True
            else:
                print("Password Mismatch")
                print("Try Again!")

        while (emailDuplicate != 0):
            emailId = input("Email : ")
            emailDuplicate = int(cursor.execute("SELECT * FROM UserData WHERE Email = '{}';".format(emailId)))
            if (emailDuplicate != 0):
                print("EMAIL ALREADY USED")
                print("Try Again!")

        regis = input("Register(y/n): ")
        if(regis=="y"):
            register(firstName,lastName,password,userName,emailId)
            print("\n")

    elif(ch==3):
        break

    else:
        print("INVALID CHOICE")
        print("\n")
    db.close();
python mysql-python python-3.7
2个回答
0
投票

假设您托管的MySql数据库的IP为xxx.xxx.xx.xx,并且它具有一个用户(例如,密码为rootPASS)和一个数据库(例如USERS)。

使用PyMySQL,可以通过用代码中的IP替换'localhost'来连接到它。

示例:

...
db = pymysql.connect("xxx.xxx.xx.xx","root","pass","UERS")
cursor = db.cursor()
...

请确保已设置数据库实例,使其可以在任何地方(*或最好是从您想连接的地方)]

您可以使用以下命令使用MySQL client验证连接:

mysql -h xxx.xxx.xx.xx -u root -pPASS

# To see the list of databases after getting connected
>show databases;

0
投票

从哪里开始?您可能会采取几种方法,但到目前为止,最常见的方法是使用基于HTMLCSSJavaScript的演示前端,并使用Python编写服务器端后端。 >

  1. 因此,如果您还不了解HTML,CSS和JavaScript,则需要学习这些技术。
  2. 您需要在Internet服务提供商(ISP)处获得一个帐户,这样您才能拥有一个托管应用程序的网站。
  3. 理想情况下,ISP将支持Web Server Gateway Interface(WSGI)Python应用程序。如果没有,则必须编程为Common Gateway Interface(CGI)规范。
  4. 您至少需要一个登录页面,该页面将输出HTML form,该页面将接受用户ID和密码并登录用户并在session中维护登录信息。成功登录后,用户将重定向
  5. 到您的页面,该页面具有用于发送消息或查看旧消息的表格。
  6. 您希望将邮件存储在数据库中。否则,您将需要实现locking机制来序列化对文件的访问。
  7. 我还没有解释HTMLCSSJavaScriptWSGICGI等是什么,这将花费很长时间。这是供您调查。

© www.soinside.com 2019 - 2024. All rights reserved.