Как обновить данные, хранящиеся в таблице sqlite в C # с пользовательским вводом - PullRequest
0 голосов
/ 06 января 2019

Я хочу обновить имя пользователя и пароль, хранящиеся в базе данных SQLite, на новые имя пользователя и пароль, предоставленные пользователем, чтобы они могли обновить свои данные пользователя.

Я уже пытался найти решения своей проблемы и нашел похожих пользователей с похожим требованием, но когда я пытаюсь реализовать их решения с помощью своего кода, похоже, что он не работает.

SQLiteConnection con = new SQLiteConnection("Data Source=Users.sqlite;Version=3;");

SQLiteCommand cmd = new SQLiteCommand("select * from UserInfo where username like @username and password = @password;", con);
cmd.Parameters.AddWithValue("@username", oldusername);
cmd.Parameters.AddWithValue("@password", oldpassword);
con.Open();

SQLiteDataReader sdr = cmd.ExecuteReader();

if ((sdr.Read() == true))
{
    MessageBox.Show("Username and Password Updated Successfully!",
                    "Task Completed");

    string update ="UPDATE UserInfo SET UserName='" + newusername + "', Password='" + newpassword + "'  WHERE (Username='" + oldusername + "' AND Password ='" + oldusername + "');";
    con.Close();
}
else
{
    MessageBox.Show("Invalid username or password",
                    "Incorrect details entered");
}

Проблема в том, что мой код проверяет, сохранено ли старое имя пользователя и пароль в таблице UserInfo, но не обновляет таблицу новыми именами пользователей и паролями. Я не знаю, что я делаю неправильно, поэтому было бы здорово, если бы кто-то мог исправить меня и, возможно, улучшить код. Заранее спасибо.

1 Ответ

0 голосов
/ 06 января 2019

Вам нужно больше узнать об основах c # и sql

Здесь навыки, используемые здесь, читают их:

Вот рабочий код

using System;
using System.Collections.Generic;
using System.Data.SQLite;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApp4
{
    class Program
    {
        static void Main(string[] args)
        {
            using (var con = new SQLiteConnection("Data Source=Users.sqlite;Version=3;"))
            using (var cmd = new SQLiteCommand())
            {

                cmd.Connection = con;
                con.Open();


                var cmd1 = @"
                    DROP TABLE IF EXISTS UserInfo;
                    CREATE TABLE IF NOT EXISTS UserInfo(username varchar(255),password 
                                  varchar(255),CONSTRAINT u_username UNIQUE (username));
                    INSERT INTO UserInfo(username,password) VALUES ('mohamed', '12345');
                    ";
                var cmd2 = @"select count(*) from UserInfo where username = @curent_username
                                and password = @curent_password;";
                var cmd3 = @"UPDATE UserInfo SET UserName = @new_username , Password= @new_password
                            where username = @curent_username and password = @curent_password;";


                cmd.CommandText = cmd1;
                cmd.ExecuteNonQuery();

                cmd.CommandText = cmd2;
                cmd.Parameters.AddWithValue("@curent_username", "mohamed");
                cmd.Parameters.AddWithValue("@curent_password", "12345");
                var userCount = (long)cmd.ExecuteScalar();
                if (userCount == 1)
                {
                    cmd.CommandText = cmd3;
                    cmd.Parameters.AddWithValue("@new_username", "adam");
                    cmd.Parameters.AddWithValue("@new_password", "6789");
                    var result = (Int32)cmd.ExecuteNonQuery();
                    if (result == 1)
                    {
                        Console.WriteLine("Username and Password Updated Successfully! | Task Completed");
                    }
                }
                else
                {
                    Console.WriteLine("Invalid username or password |Incorrect details entered");
                }
            }

            Console.ReadLine();
        }

    }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...