动态连接数据库.mdf并获取该数据库中的所有表

本文关键字:数据库 获取 连接 mdf 动态 | 更新日期: 2023-09-27 17:50:37

我的程序应该能够选择任何db(.mdf)并显示此db中的所有表。例如,表"students"有一个字段:"firstName"、"SecondName"、"dateOfBirth"。但我收到一个错误,访问拒绝。操作系统错误5或32.

// Open db
        private void btnOpenDatavase_Click(object sender, EventArgs e)
        {
            Stream myStream = null;
            OpenFileDialog openFileDialog1 = new OpenFileDialog();
            openFileDialog1.InitialDirectory = "c:''";
            openFileDialog1.Filter = "Data|*.mdf";
            openFileDialog1.FilterIndex = 2;
            openFileDialog1.RestoreDirectory = false;
            if (openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                try
                {
                    if ((myStream = openFileDialog1.OpenFile()) != null)
                    {
                        using (myStream)
                        {
                            string fullPath = openFileDialog1.FileName;
                            showTables(fullPath);
                        }
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show("Original error: " + ex.Message);
                }
            }
        }
        void showTables(string path)
        {
            String strConnection = @"Data Source=.'SQLEXPRESS;
                          AttachDbFilename=" + path + ";" +
                          "Integrated Security=True;" +
                          "Connect Timeout=30;" +
                          "User Instance=False";
            SqlConnection con = new SqlConnection(strConnection);
            try
            {
                con.Open();
                SqlCommand sqlCmd = new SqlCommand();
                sqlCmd.Connection = con;
                sqlCmd.CommandType = CommandType.Text;
                sqlCmd.CommandText = "SELECT * FROM INFORMATION_SCHEMA.TABLES";
                SqlDataAdapter sqlDataAdap = new SqlDataAdapter(sqlCmd);
                DataTable dtRecord = new DataTable();
                sqlDataAdap.Fill(dtRecord);
                comboBox1.DataSource = dtRecord;
                comboBox1.DisplayMember = "TABLES";
                con.Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

}

动态连接数据库.mdf并获取该数据库中的所有表

您得到的具体异常消息是什么?

请从连接字符串中删除"User Instance=False",然后再试一次。您的代码可以成功地连接到mdf文件与新的连接?

请让我知道它是否适合你。