【问题标题】:How do I use a database in a C++/CLR project in Visual Studio?如何在 Visual Studio 的 C++/CLR 项目中使用数据库?
【发布时间】:2021-08-31 07:42:21
【问题描述】:

我正在尝试制作一个存储一些文本的应用,所以我想使用数据库连接(不鼓励文件 I/O)?还有,我如何学习以及从哪里学习? 我不知道如何开始,从什么开始等等,我已经制作了 GUI 并想让它工作!

【问题讨论】:

  • 我会用 C# 来做。
  • 我使用VS开发Windows应用。我用 C# 和 C++(和其他语言)编程。如果你使用CLR,对我来说这意味着你可能应该使用C#(或F#)。最好的起点是一本好的入门和/或教程书。如果你选择 F#,我推荐The Book of F#。如果您选择 C#,我没有特别推荐的书籍 — 可能来自 Microsoft Press 或 O'Reilly。
  • @Darpan,有更新吗?请检查我的答案是否适合您。

标签: database visual-studio winforms c++-cli


【解决方案1】:

您可以参考以下代码将一些信息从文本框中插入到数据库中。

private: System::Void button1_Click(System::Object^ sender, System::EventArgs^ e) {
        String^ connstr = "connstr";
        SqlConnection^ connection = gcnew SqlConnection(connstr);
        connection->Open();
        String^ sql = "Insert into Employee(ID,Name,Address)values(@ID,@Name,@Address)";
        SqlCommand^ command = gcnew SqlCommand(sql, connection);
        command->Parameters->AddWithValue("@ID", txtID->Text);
        command->Parameters->AddWithValue("@Name",txtName->Text);
        command->Parameters->AddWithValue("@Address", txtAddress->Text);
        command->ExecuteNonQuery();
        connection->Close();
        MessageBox::Show("success");



    }
    private: System::Void button2_Click(System::Object^ sender, System::EventArgs^ e) {
        dataGridView1->DataSource = 0;
        String^ connstr = "connstr";
        SqlConnection^ connection = gcnew SqlConnection(connstr);
        connection->Open();
        String^ sql = "Select * from Employee";
        //SqlCommand^ command = gcnew SqlCommand(sql, connection);
        SqlDataAdapter^ adapter = gcnew SqlDataAdapter(sql, connection);
        DataTable^ table = gcnew DataTable();
        adapter->Fill(table);
        dataGridView1->DataSource = table;
        connection->Close();

    }

注意:Button1_click 用于向数据库插入数据。 Button2_click 用于在 datagridview 中显示来自数据库的数据。请使用\\ 替换连接字符串中的\

结果:

【讨论】:

  • 谢谢,杰克!您的回答很有用,但我无法投票。对不起!
  • @Darpan,关于我的回答还有其他问题吗?如果没有,您可以单击“✔”将您的回复标记为答案。它还将帮助其他人解决类似的问题。
  • 杰克,仅此而已,但我对此,很抱歉再问你一个问题?我如何指定数据库的来源,或者我的程序定位它??你能帮帮我吗?
  • @Darpan,您可以参考链接了解如何从数据库获取连接字符串。 How to get the connection String from a database
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-12-01
  • 2011-10-02
  • 2010-10-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多