zoukankan      html  css  js  c++  java
  • ADO.NET 常用操作

    一、增删改:
    // 1. SQL语句
    string sql = "insert / update / delete";

    // 2. 创建连接对象
    string connStr = "server=.;database=数据库;uid=sa;pwd=sa";
    SqlConnection conn = new SqlConnection(connStr);

    // 3. 创建执行对象
    SqlCommand comm = new SqlCommand(sql, conn);

    // 4. 打开连接
    conn.Open();

    // 5. 执行,获取受影响行数
    int count = comm.ExecuteNonQuery();

    // 6. 关闭连接
    conn.Close();

    // 7. 处理
    if(count>0)
    MessageBox.Show("操作成功");
    else
    MessageBox.Show("操作失败");


    二、查询首行首列
    // 1. SQL语句
    string sql = "select ....";

    // 2. 创建连接对象
    string connStr = "server=.;database=数据库;uid=sa;pwd=sa";
    SqlConnection conn = new SqlConnection(connStr);

    // 3. 创建执行对象
    SqlCommand comm = new SqlCommand(sql, conn);

    // 4. 打开连接
    conn.Open();

    // 5. 执行,获取结果
    string result = (string)comm.ExecuteScalar();

    // 6. 关闭连接
    conn.Close();


    三、查询多条数据(ListView)
    // 1. SQL语句
    string sql = "select * from 表";

    // 2. 创建连接对象
    string connStr = "server=.;database=数据库名;uid=sa;pwd=sa";
    SqlConnection conn = new SqlConnection(connStr);

    // 3. 创建执行对象
    SqlCommand comm = new SqlCommand(sql, conn);

    // 4. 打开连接
    conn.Open();

    // 5. 执行,获取查询对象
    SqlDataReader reader = comm.ExecuteReader();

    // 6. 遍历结果
    while(reader.Read())
    {
    int id = Convert.ToInt32(reader["id"]);
    string name = reader["name"].ToString();
    // ....
    }

    // 7. 关闭对象
    reader.Close();
    conn.Close();


    四、适配器,批量查询
    // 1. SQL语句
    string sql = "select * from 表";

    // 2. 连接地址
    string connStr = "server=.;database=数据库;uid=sa;pwd=sa";
    SqlDataAdapter sda = new SqlDataAdapter(sql, connStr);

    // 3. 填充结果
    DataTable dt = new DataTable();
    sda.Fill(dt);

    // 4. 绑定数据源
    // 4.1. 绑定下拉框
    this.combobox.DisplayMember = "Name";
    this.combobox.ValueMember = "Id";
    this.combobox.DataSource = dt;

    // 4.2. 绑定DataGridView
    this.datagridview.DataSource = dt;

  • 相关阅读:
    spring boot welcome-file-list
    spring boot web.xml listener
    Linkflow CDP
    连接数据,构建中台,Linkflow如何推动数据化浪潮 CDP
    客户全生命周期服务解决方案的提供商。
    自然语言处理的发展历史 发展方向 行业(法律)
    SpringBoot 设置 profiles 并在其他配置文件里面读取 pom.xml
    SpringBoot 配置文件无法解析占位符
    微服务 SaaS 低代码开发平台
    混沌工程与分布式系统
  • 原文地址:https://www.cnblogs.com/lecj2498/p/8185508.html
Copyright © 2011-2022 走看看