简体   繁体   中英

How do i store data in a service-based database?

I am trying to store the username and password inside a table called 'User' which is inside a service-based database.

Below is code of what i have tried.

private void Btn_register_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                //Create the conection string and open the conn
                SqlConnection conne = new SqlConnection(@"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=\\CUC-SRV-FS02\Studio-StuHome$\13mihailovs.m\Documents\IT_Unit4\IT_Unit4\ITUnit4.mdf;Integrated Security=True");


                //Open the connection string
                conne.Open();

                //Get all the values from the text boxes etc and pass them over to the DB
                string insertQuery = "insert into User(Username, Password) " +
                    "values(@Username, @Password)";
                SqlCommand com = new SqlCommand(insertQuery, conne);

                //Get values from the controls such as the text boxes and pass them over to the DB
                com.Parameters.AddWithValue("@Username", txt_username.Text);
                com.Parameters.AddWithValue("@Password", txt_password.Text);

                //This actually executes the query with the given values above.
                com.ExecuteNonQuery();

                //Dispose the connection string once the data has been passed over the DB
               conne.Close();

            }
            catch (Exception problem)
            {
                MessageBox.Show("error has occured");
            }
        }

currect way for insert into database in Ado.Net:

    private readonly SqlConnection _con = new SqlConnection("Data Source=.;Initial 
    Catalog=dbPhoneBook;Integrated Security=True");

public string Add(string user , string pass)
    {
        string result = "";
        SqlCommand cmd = new SqlCommand();
        try
        {
            cmd.Connection = _con;
            cmd.CommandText = "insert into tbl_login(user,pass)values(@user,@pass)";
            cmd.Parameters.AddWithValue("@user", user);
            cmd.Parameters.AddWithValue("@pass", pass);
            if (_con.State != ConnectionState.Open)
            {
                _con.Open();
            }
            cmd.ExecuteNonQuery();
            result = "Ok";
            cmd.Dispose();
        }
        catch
        {
            cmd.Dispose();
            result = "NOk";

        }
        return result;
    }

Also check the following Check out the web site https://www.connectionstrings.com/ link to the database.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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