繁体   English   中英

如何将c#控制台连接到数据库?

[英]How do I connect c# console to database?

我正在制作ac#控制台应用程序,并想添加一个登录系统。

我已经有以下代码:

Start:
        Console.Clear();
        Console.ForegroundColor = ConsoleColor.Cyan;

        Console.WriteLine("Enter Username.");
        string strUsername = Console.ReadLine();
        string strTUsername = "Test";

        if (strUsername == strTUsername)
        {
            Console.Clear();
            Console.WriteLine("Enter Password");
            Console.ForegroundColor = ConsoleColor.Gray;
            string strPassword = Console.ReadLine();
            string strTPassword = "Test";
            if ( strPassword == strTPassword)
            {
                Console.Write("Logging in.");
                Thread.Sleep(1000);
            }

            else
            {
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine("The password you entered is wrong.");
                Thread.Sleep(2000);
                goto Start;
            }
        }

        else
        {
            Console.ForegroundColor = ConsoleColor.Red;
            Console.WriteLine("The username you entered is wrong.");
            Thread.Sleep(2000);
            goto Start;
        }

我想让它允许您输入多个可以使用的用户名和密码。

到目前为止,它只接受用户名和密码“ Test”,但我想将其链接到另一个可以填充用户名和密码的文件,而不仅仅是“ Test”。

您可以给我或提供的任何帮助都非常有用!

您有两种方法可以做到:

1: Database to store username and password
2: Save the username and password in file in a uniform format(like comma,tab separated)

1:数据库

->Select a database to use
->create a table with columns such as username and password
->connect to database from your app
->get username from console and compare it with the rows of database and check if the password given is correct.

2:文件

->Save a file with username and password with a certain format(comma,space or tab separated)
->Import those from the file to a Dictionay<users>.
->compare the entered password and user name with the dictionary items.

您可以使用加密使文件或数据库更安全。

static void Main(string[] args)
        {
            List<User> usersList = new List<User>();
            string[] lines = System.IO.File.ReadAllLines("users.txt");
            foreach ( var line in lines)
            {
                User user = new User();
                user.user = line.Split(' ')[0];
                user.password = line.Split(' ')[1];
                usersList.Add(user);
            }
            foreach (var item in usersList)
            {
                Console.WriteLine(item.user);
                Console.WriteLine(item.password);
            }
            Console.ReadLine();
        }



}
public class User
{
   public string user { get; set; }
   public  string password { get; set; }
}

在此,我添加了一个简单的代码来读取以空格分隔的密码文件,并根据您的要求使用它。 为了更安全,可以加密文件。 谢谢

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM