Connection error while performing query

0

I'm a beginner in programming and I'm trying to connect to a database. But when I click the "Search" button to browse the database and display values on my screen, the following error is generated through a messagebox that I put in Catch:

  

"" An attempt to attach an auto-named database to C: \   database file). A database with the same name exists, or   specified file can not be opened, or it is located on UNC share. ""

Below is my code for connecting and displaying values:

namespace trenodb
{
    public partial class Form1 : Form
    {
        static string strDb = "Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=\"C:\Users\aRtHuRz\Documents\Visual Studio 2015\Projects\trenodb\trenodb\dbTrenodb.mdf\";Integrated Security=True;Connect Timeout=30";

    public Form1()
    {
        InitializeComponent();
    }

    private void btnPesquisar_Click(object sender, EventArgs e)
    {
        string pesquisar = "SELECT * FROM Table WHERE [Id] = " + txtID;
        SqlConnection conexao = new SqlConnection(strDb);
        SqlCommand cmd = new SqlCommand(pesquisar, conexao);
        SqlDataReader DR;
        try
        {
            conexao.Open();
            DR = cmd.ExecuteReader();
            if (DR.Read())
            {
                txtID.Text = DR.GetValue(0).ToString();
                txtNome.Text = DR.GetValue(1).ToString();
                txtFone.Text = DR.GetValue(2).ToString();
                txtEndereço.Text = DR.GetValue(3).ToString();
                DR.Close();
            } cmd.Dispose();
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
        finally
        {
            conexao.Close();
        }
    }
}

}

    
asked by anonymous 13.09.2016 / 21:56

1 answer

0

I'll take a step-by-step how to do to generate the connection string.

Lookforthesettingstab.

Settheconnectionstringtothedesireddatabase.

Configuredconnectionstring.

Now you can copy it and use it in the place where you pass your current one, or, use it for project properties.

Example:

string strConexao = IntegraOpLogSerraPark.Properties.Settings.Default.stringConnection;

If you notice, the stringConnection we create in the project is just after the Default property. So the configured connection string is returned.

    
14.09.2016 / 00:58