温馨提示×

winform开发框架的数据库操作

小樊
86
2024-07-11 11:36:36
栏目: 智能运维
亿速云云数据库,读写分离,安全稳定,弹性扩容,低至0.3元/天!! 点击查看>>

在WinForms开发框架中,可以使用ADO.NET技术来进行数据库操作。ADO.NET是.NET平台下的一种数据库访问技术,通过ADO.NET提供的类和方法,可以连接数据库、执行SQL语句、读取数据等操作。

以下是一个简单的示例代码,演示了如何在WinForms中使用ADO.NET来连接数据库、执行SQL查询并显示结果:

using System;
using System.Data;
using System.Data.SqlClient;
using System.Windows.Forms;

namespace WinFormsDBDemo
{
    public partial class MainForm : Form
    {
        public MainForm()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            string connectionString = "Data Source=ServerName;Initial Catalog=DatabaseName;Integrated Security=True";
            string query = "SELECT * FROM TableName";

            using (SqlConnection connection = new SqlConnection(connectionString))
            {
                SqlCommand command = new SqlCommand(query, connection);

                connection.Open();

                SqlDataAdapter adapter = new SqlDataAdapter(command);
                DataTable dataTable = new DataTable();
                adapter.Fill(dataTable);

                dataGridView1.DataSource = dataTable;
            }
        }
    }
}

在上面的示例代码中,我们首先定义了数据库连接字符串connectionString和SQL查询语句query。然后在按钮点击事件中,我们创建了一个SqlConnection对象来连接数据库,并使用SqlCommand对象执行查询。通过SqlDataAdapter对象将查询结果填充到一个DataTable中,最后将DataTable绑定到一个DataGridView控件上显示查询结果。

需要注意的是,上面的示例代码中使用了集成安全性(Integrated Security=True)来连接数据库,也可以使用用户名和密码来进行连接。另外,在实际开发中,还需要处理异常、关闭数据库连接等操作,以保证程序的稳定性和安全性。

亿速云「云数据库 MySQL」免部署即开即用,比自行安装部署数据库高出1倍以上的性能,双节点冗余防止单节点故障,数据自动定期备份随时恢复。点击查看>>

推荐阅读:c# winform的数据库操作

0