如何从在线(托管)mysql 数据库访问和编辑数据
How to access and edit data from online(hosted) mysql database
我正在制作一个类似聊天室的小程序,用户可以在其中注册、登录、发送和接收消息(在 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();
从哪里开始?您可能可以采用多种方法,但到目前为止,最常见的方法是使用基于 HTML
、CSS
和 JavaScript
的演示前端以及服务器端后端 -结尾写在Python.
- 因此,如果您还不知道 HTML、CSS 和 JavaScript,则需要学习这些技术。
- 您需要从 Internet 服务提供商 (ISP) 获得一个帐户,这样您才能拥有一个托管您的应用程序的网站。
- 理想情况下,ISP 将支持
Web Server Gateway Interface
(WSGI) Python 应用程序。否则,您将必须按照 Common Gateway Interface
(CGI) 规范进行编程。
- 您至少需要一个登录页面,该页面将输出一个 HTML
form
,该页面将接受用户 ID 和密码并登录用户并在 session
中维护登录信息.成功登录后,用户将重定向到您的页面,该页面将包含用于发送消息或查看旧消息的表单。
- 您希望将您的消息存储在数据库中。否则,您将需要实施
locking
机制来序列化对文件的访问。
我还没有解释什么是 HTML
、CSS
、JavaScript
、WSGI
、CGI
等等——这也需要长。这是给你调查的。
假设您有一个 MySql 数据库托管,其 IP 为 xxx.xxx.xx.xx
并且它有一个用户(例如 root
,密码 PASS
)和一个数据库(例如 USERS
).
使用 PyMySQL,您可以通过将 'localhost' 替换为代码中的 IP 来连接到它。
示例:
...
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;
我正在制作一个类似聊天室的小程序,用户可以在其中注册、登录、发送和接收消息(在 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();
从哪里开始?您可能可以采用多种方法,但到目前为止,最常见的方法是使用基于 HTML
、CSS
和 JavaScript
的演示前端以及服务器端后端 -结尾写在Python.
- 因此,如果您还不知道 HTML、CSS 和 JavaScript,则需要学习这些技术。
- 您需要从 Internet 服务提供商 (ISP) 获得一个帐户,这样您才能拥有一个托管您的应用程序的网站。
- 理想情况下,ISP 将支持
Web Server Gateway Interface
(WSGI) Python 应用程序。否则,您将必须按照Common Gateway Interface
(CGI) 规范进行编程。 - 您至少需要一个登录页面,该页面将输出一个 HTML
form
,该页面将接受用户 ID 和密码并登录用户并在session
中维护登录信息.成功登录后,用户将重定向到您的页面,该页面将包含用于发送消息或查看旧消息的表单。 - 您希望将您的消息存储在数据库中。否则,您将需要实施
locking
机制来序列化对文件的访问。
我还没有解释什么是 HTML
、CSS
、JavaScript
、WSGI
、CGI
等等——这也需要长。这是给你调查的。
假设您有一个 MySql 数据库托管,其 IP 为 xxx.xxx.xx.xx
并且它有一个用户(例如 root
,密码 PASS
)和一个数据库(例如 USERS
).
使用 PyMySQL,您可以通过将 'localhost' 替换为代码中的 IP 来连接到它。
示例:
...
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;