简体   繁体   English

使用 C# 连接到数据库

[英]Connection to database with C#

I am trying to connect to a database for my Login wpf.我正在尝试为我的登录名 wpf 连接到数据库。

SqlConnectionStringBuilder mConnectionBuilder = new SqlConnectionStringBuilder
{
    DataSource = @"(LocalDB)\MSSQLLocalDB",
    InitialCatalog = "UserData"               
};

using (SqlConnection mConnection = new SqlConnection(mConnectionBuilder.ConnectionString))
{
    SqlCommand mCommand = new SqlCommand
    {
        Connection = mConnection,
        CommandText = "Select Id, Username, E-Mail, Password from Users"
    };

    if (mConnection.State == ConnectionState.Closed)
    {
        mConnection.Open();
    }

    using (SqlDataReader mReader = mCommand.ExecuteReader())
    {
        while (mReader.Read())
        {
            string mUsername = Convert.ToString(mReader.GetValue(1));
            string mPassword = Convert.ToString(mReader.GetValue(2));

            if (txtLoginUsername.Text == mUsername && txtLoginPassword.Text == mPassword)
            {
                loginSuccessful = true;
            }
            else
            {
                MessageBox.Show("Wrong username or password");
            }
        }
    }
}

I created the database in Visual Studio and named it UserData.我在 Visual Studio 中创建了数据库并将其命名为 UserData。 But at mConnection.Open() i get an SqlException "Cannot open database "UserData" requested by the login. The login failed. Login failed for user (myUserName)".但是在 mConnection.Open() 我得到一个 SqlException“无法打开登录请求的数据库“UserData”。登录失败。用户(myUserName)登录失败“。 I know there are different ways to use SQL with C# but I want it to work that way really hard because I waisted way too much time to find a solution for this problem.我知道有不同的方法可以将 SQL 与 C# 一起使用,但我希望它能够以这种方式非常努力地工作,因为我花了太多时间来寻找解决这个问题的方法。 I hope i can get some helpful information here:)我希望我能在这里得到一些有用的信息:)

String connetionString = null;
SqlConnection cnn;

connetionString = "Data Source=ServerName;Initial Catalog=DatabaseName;User ID=UserName;Password=Password"
cnn = new SqlConnection(connetionString);
try
{
    cnn.Open();
    MessageBox.Show ("Connection Open ! ");
    cnn.Close();
}
catch (Exception ex)
{
    MessageBox.Show("Can not open connection ! ");
}

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

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