首页 > 解决方案 > 如何在python服务器中连接sql3

问题描述

我在 python 中编写了简单的服务器,但它无法写入和读取 sqldatabase。

服务器连接到 android java 程序,数据通过正常,但服务器不写入或读取 sql。

import json
import socket
import threading
import sqlite3
import time

IP = "0.0.0.0"
PORT = 6040

# the connection to the sql database

#####db_connection = sqlite3.connect('asia.db')
# sqlite3.connect connect to database

#####cursor = db_connection.cursor()


# The command cursor creates a pipe (called cursor) to the database through which you can run queries,
# perform actions and get their answers.

# cursor.execute('''CREATE TABLE users(user text UNIQUE, password text, fname text, lname text)''')


def add(user: str, password: str, fname: str, lname: str):
    # adds the current user to the database if his user name isnt already exist - user (UNIQUE)
    try:
        con = sqlite3.connect('asia.db')
        cur = con.cursor()
        cur.execute("INSERT INTO users VALUES (?, ?, ?, ?)",
                  (user, password, fname, lname))
        con.commit()  # Save (commit) the changes
        print("changes saved")
        return True
    except sqlite3.IntegrityError as unique_exception:
        print(f"{unique_exception}, User already registered")
        return False


def login(user: str, password: str):
    # finds if user in this username exist in the database and if the passwords between the emails matches

    con = sqlite3.connect('asia.db')
    cur = con.cursor()
    db_user = cur.execute(f"SELECT user From users Where user = '{user}'")  # check if user exist

    if db_user.fetchone() is None:
        return False
    else:
        db_password = cur.execute(f"SELECT Password From users Where user = '{user}'")  # index
        if db_password:
            db_password = db_password.fetchone()[0]  # getting out of the index
            if db_password == password:
                return True
            else:
                return False
        else:  # password incorrect
            return False


def request_handler(json_request, client_socket):
    # handles request by the value of the request key of the object
    print(json_request)
    if json_request["request"] == "add":

        if add(
                json_request["user"],
                json_request["password"],
                json_request["fname"],
                json_request["lname"]
        ):
            print(json_request["user"], "is registered")
            json_response = {"response": "welcome"}
            client_socket.send(json.dumps(json_response).encode())
        else:
            print(json_request["user"], "is already exist")
            json_response = {"response": "email already exist"}
            client_socket.send(json.dumps(json_response).encode())

    elif json_request["request"] == "login":
        if login(json_request["user"], json_request["password"]):
            print("login succeed")
            json_response = {"response": "Hey there"}
            client_socket.send(json.dumps(json_response).encode())

        else:
            print("login didn't succeed")
            json_response = {"response": "Login didn't succeed"}
            client_socket.send(json.dumps(json_response).encode())

    else:
        print("invalid data")
        json_response = {"response": "Check again"}
        client_socket.send(json.dumps(json_response).encode())
        client_socket.close()


def handle_connection(client_socket: socket.socket, ip_address: str):
    # the connection to the client

    print("new connection from:", ip_address)
    request = client_socket.recv(1024).decode()
    json_request = json.loads(request)  # Loads the data(string) to the json object
    request_handler(json_request, client_socket)  # starts handling the clients request
    client_socket.close()


def main():
    server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    server_socket.bind((IP, PORT))
    print("Starting server...")
    print("port = ", PORT)
    print("ip = ", IP)

    server_socket.listen()

    while True:
        new_client = server_socket.accept()
        new_thread = threading.Thread(target=handle_connection,
                                      args=new_client)  # Creating a thread to handle the connection
        new_thread.start()  # starts the handling process


if __name__ == '__main__':
    main()

标签: pythonsqlite

解决方案


推荐阅读