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;

  • 相关阅读:
    学习笔记
    display:inline、block、inline-block的区别
    响应式布局设计
    CSS中position属性三大定位方式讲解
    CSS position 属性 一定要有width
    JQuery中each()怎么跳出
    JSON 学习笔记
    【转】30个你不可不知的CSS选择器
    HTML文档类型的作用,文档类型有多少种?
    jQuery中children()与find()的区别
  • 原文地址:https://www.cnblogs.com/lecj2498/p/8185508.html
Copyright © 2011-2022 走看看