码迷,mamicode.com
首页 > Web开发 > 详细

ADO.NET 常用操作

时间:2018-01-03 22:31:56      阅读:254      评论:0      收藏:0      [点我收藏+]

标签:log   query   div   his   select   connect   let   idv   and   

一、增删改:
// 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;

ADO.NET 常用操作

标签:log   query   div   his   select   connect   let   idv   and   

原文地址:https://www.cnblogs.com/lecj2498/p/8185508.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!