从 SQL Server Express 数据库中读取表

Posted

技术标签:

【中文标题】从 SQL Server Express 数据库中读取表【英文标题】:Reading tables from SQL Server Express database 【发布时间】:2016-11-16 17:47:19 【问题描述】:

我正在尝试在 SQL Server Express 中读取我的数据库中包含的表,但它一直为空。到底做错了什么?

private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)

    string connectionString = "Data Source=LPMSW09000012JD\\SQLEXPRESS;Initial Catalog=Pharmacies;Integrated Security=True";

    string query = "SELECT * FROM INFORMATION_SCHEMA.TABLES";

    using (SqlConnection connection = new SqlConnection(connectionString))
    
        SqlCommand command = new SqlCommand(query, connection);
        command.Connection.Open();

        command.ExecuteNonQuery();
    

已更新但仍为空:

  private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
    
        try 

            string connectionString = "Data Source=LPMSW09000012JD\\SQLEXPRESS;Initial Catalog=Pharmacies;Integrated Security=True";
            SqlConnection con2 = new SqlConnection(connectionString);
            con2.Open();
            string query = "SELECT * FROM INFORMATION_SCHEMA.TABLES";
            SqlCommand cmd2 = new SqlCommand(query, con2);

            SqlDataReader dr2 = cmd2.ExecuteReader();
            while (dr2.Read())
            

                comboBox1.Items.Add((string)dr2[0]);

            


        


        catch (Exception ex)
        

            MessageBox.Show(ex.ToString());
        

最新更新的代码。我想我想通了,但仍然显示为空:

 private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
    
        try 

            string connectionString = "Data Source=LPMSW09000012JD\\SQLEXPRESS;Initial Catalog=Pharmacies;Integrated Security=True";
            SqlConnection con2 = new SqlConnection(connectionString);
            con2.Open();
            string query = "SELECT * FROM INFORMATION_SCHEMA.TABLES ";
            SqlCommand cmd2 = new SqlCommand(query, con2);

            SqlDataReader dr2 = cmd2.ExecuteReader();
            while (dr2.Read())
            

                string Dtables = dr2.GetString(dr2.GetOrdinal("TABLE_NAME"));
                comboBox1.Items.Add(Dtables);

            

        

        catch (Exception ex)
        

            MessageBox.Show(ex.ToString());
        

全班:

    namespace unique_database public partial class Form1 : Form

    public Form1()
    
        InitializeComponent();
    

    private void button1_Click(object sender, EventArgs e)
    

    

    private void button2_Click(object sender, EventArgs e)
    
        string connectionString = "Data Source=LPMSW09000012JD\\SQLEXPRESS;Initial Catalog=Pharmacies;Integrated Security=True";
        string query = "CREATE TABLE [dbo].[" + textBox1.Text + "](" + "[Code] [varchar] (13) NOT NULL," +
       "[Description] [varchar] (50) NOT NULL," + "[NDC] [varchar] (50) NULL," +
        "[Supplier Code] [varchar] (38) NULL," + "[UOM] [varchar] (8) NULL," + "[Size] [varchar] (8) NULL,)";


        using (SqlConnection connection = new SqlConnection(connectionString))
        
            SqlCommand command = new SqlCommand(query, connection);
            command.Connection.Open();
            command.ExecuteNonQuery();
        

        SqlConnection con = new SqlConnection("Data Source=LPMSW09000012JD\\SQLEXPRESS;Initial Catalog=Pharmacies;Integrated Security=True");
        string filepath = textBox2.Text; //"C:\\Users\\jdavis\\Desktop\\CRF_105402_New Port Maria Rx.csv";
        StreamReader sr = new StreamReader(filepath);
        string line = sr.ReadLine();
        string[] value = line.Split(',');
        DataTable dt = new DataTable();
        DataRow row;
        foreach (string dc in value)
        
            dt.Columns.Add(new DataColumn(dc));
        

        while (!sr.EndOfStream)
        
            value = sr.ReadLine().Split(',');
            if (value.Length == dt.Columns.Count)
            
                row = dt.NewRow();
                row.ItemArray = value;
                dt.Rows.Add(row);
            
        
        SqlBulkCopy bc = new SqlBulkCopy(con.ConnectionString, SqlBulkCopyOptions.TableLock);
        bc.DestinationTableName = textBox1.Text;
        bc.BatchSize = dt.Rows.Count;
        con.Open();
        bc.WriteToServer(dt);
        bc.Close();
        con.Close();

    

    private void button3_Click(object sender, EventArgs e)
    
        OpenFileDialog openFileDialog = new OpenFileDialog();
        openFileDialog.Filter = "CSV files (*.csv)|*.csv|XML files (*.xml)|*.xml";


        if (openFileDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
        
            this.textBox2.Text = openFileDialog.FileName;
        
    

    private void FillCombo()
    
        try
        

            string connectionString = "Data Source=LPMSW09000012JD\\SQLEXPRESS;Initial Catalog=Pharmacies;Integrated Security=True";
            using (SqlConnection con2 = new SqlConnection(connectionString))
            
                con2.Open();
                string query = "SELECT * FROM INFORMATION_SCHEMA.TABLES ";
                SqlCommand cmd2 = new SqlCommand(query, con2);

                SqlDataReader dr2 = cmd2.ExecuteReader();
                while (dr2.Read())
                
                    int col = dr2.GetOrdinal("TABLE_NAME");
                    comboBox1.Items.Add(dr2[col].ToString());
                

            
        
        catch (Exception ex)
        
            MessageBox.Show(ex.ToString());
        
    

【问题讨论】:

你需要读入类似 DataReader 的东西。 ExecuteNonQuery 用于不返回值/数据的 INSERT 之类的东西。 更新了代码但仍然是空的@DonBoitnott 有多难?? ***.com/questions/14113931/… @Fourat 这不是我想要的。 @Fourat 表示表格,而不是表格值。我已经知道该怎么做了 【参考方案1】:

好的,首先,不要使用comboBox1_SelectedIndexChanged 来填充comboBox1。 使用YourForm.OnLoad 事件、表单构造函数或单击按钮,但不要使用SelectedIndexChanged 填充自身,因为每次选择comboBox1 中的一项时都会执行此过程。

要获取列索引,只需使用:dr2.GetOrdinal("TABLE_NAME");

private void FillCombo()

    try 
    
        string connectionString = "Data Source=LPMSW09000012JD\\SQLEXPRESS;Initial Catalog=Pharmacies;Integrated Security=True";
        using (SqlConnection con2 = new SqlConnection(connectionString))
        
            con2.Open();
            string query = "SELECT * FROM INFORMATION_SCHEMA.TABLES";
            SqlCommand cmd2 = new SqlCommand(query, con2);

            SqlDataReader dr2 = cmd2.ExecuteReader();
            while (dr2.Read())
            
                int col = dr2.GetOrdinal("TABLE_NAME");
                comboBox1.Items.Add(dr2[col].ToString());
            
        
    
    catch (Exception ex)
    
        MessageBox.Show(ex.ToString());
    

【讨论】:

由于某种原因仍然是空的 您的数据库中有表吗?如果在 SSMS 中使用 select 语句,会有多少结果?你打开组合框了吗? 删除真题代码,粘贴全班。 是的,我已经打开了组合框,是的,我确实有表格。其中 4 个。我运行了"SELECT * FROM INFORMATION_SCHEMA.TABLES ",然后出现了 TABLE_CATALOG、TABLE_SCHEMA、TABLE_NAME 和 TABLE_TYPE。将其缩小到这个命令”SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES 单独显示表数据,所以是的表存在 这段代码有错误,你能编译它没有错误吗?【参考方案2】:

使用 ExecuteReader() 代替 ExecuteNonQuery()。然后使用 SqlDataReader() 获取结果。

【讨论】:

@Jevon 这个答案让您知道从哪里开始。在 MSDN 上寻找有关 ExecuteReader() 的帮助,我相信你会在那里找到一些示例。 是的,我做了所有这些,但我最新更新的代码仍然是空的 @mcNets

以上是关于从 SQL Server Express 数据库中读取表的主要内容,如果未能解决你的问题,请参考以下文章

如何从 SQL Server DB 创建 SQL Server Express DB

如何从 C# 代码将 SQL Server CE 迁移到 SQL Server 2012 Express

从 SQL Server CE 切换到 SQL Server Express 实体问题

从sql server express发送电子邮件[关闭]

从 Visual Studio 2015 发布 SQL Server Express

将数据从 .txt 文件导入 SQL Server 2005 Express