代码之家  ›  专栏  ›  技术社区  ›  Aric Peters

将数据库数据插入列表框C#

  •  1
  • Aric Peters  · 技术社区  · 7 年前

    免责声明:我之前没有从c代码查询数据库的经验(所以请从容不迫)

    我正在尝试将SQL Server数据库中的数据插入列表框。现在我正在以数组的形式进行尝试。我首先连接到数据库,然后将数据库中的“状态”插入到数组的索引中。我想把所有50个状态都放到我的数组中,然后把这些信息放到我的列表框中。现在,我的数据正在插入,但当我在列表框中查看时,它会显示出来 System.Data.SqlClient.SqlCommand .

    public string connString = "Not displaying this for security reasons, it is set up correctly though."; //Setting up the connection to my DB
    
    public frmState()
    {
            InitializeComponent();
    
            this.FormClosed += new System.Windows.Forms.FormClosedEventHandler(this.frmState_FormClosed);
    
            using (SqlConnection dbConn = new SqlConnection(connString))
            {
                dbConn.Open();
                string cmdString = "select State_Name from [State]";
    
                SqlCommand cmd = new SqlCommand(cmdString, dbConn);
    
                SqlDataReader reader = cmd.ExecuteReader();
    
                try
                {
                    while (reader.Read())
                    {
                            string[] stateList = new string[50];
    
                            for (int i = 1; i <= 50; i++)
                            {
                                stateList[i - 1] = cmd.ToString();
                            }
    
                            for (int i = 0; i < stateList.Length; i++)
                            {
                                lbStates.Items.Add(stateList[i].ToString());
                            }
                    }
                }
                finally
                {
                    reader.Close();
                }
            }
        }
    

    此外,我知道,从现在起,我将显示相同的状态50次。我试图找出如何一次插入一个状态。这是一种有效的方法吗?还有,关于用c语言处理数据库的提示吗?我正在使用Visual Studio 2017和Microsoft SQL Server 2016。

    1 回复  |  直到 7 年前
        1
  •  3
  •   yekanchi    7 年前

    问题来自于你做了什么:

    stateList[i - 1] = cmd.ToString();
    

    这是错误的,因为您正在将SqlCommand对象转换为字符串,并将其放入字符串类型的数组中,以从SqlCommand中检索数据。

    按以下方式更改上述行将解决您的问题:

    tateList[i - 1] = reader.GetString(0);
    

    在c语言中使用数据库有什么提示吗?

    对于C#和SQL的初学者,我建议您继续学习ADO的基本数据库访问工具。net类似使用SqlDataReader、SqlDataReader、SqlDataAdapter等。但要有专业的,当然安全的应用程序也需要简单;你必须使用 ORM 工具(安全访问数据库的介质),如“实体框架”,linq。。。witch将使与数据库的对话更加方便。

    补充:

    我建议你阅读 this 关于如何使用SqlDataReader的教程。