C#练习DataReader
SQL代码:
create database ThreeDb
go
USE ThreeDb;
GO
CREATE TABLE classify --分类表
(
id int primary key identity(1,1),
name nvarchar(20) not null
) GO
CREATE TABLE product --产品表
(
id int primary key identity(1,1),
name nvarchar(20) not null,
price decimal,
number int default 0,
c_id int FOREIGN KEY references classify(id)
)
GO CREATE TABLE users
(
id int primary key identity(1,1),
name nvarchar(20) not null,
pwd nvarchar(20) not null
)
GO --添加分类测试数据
insert into classify(name) values('图书');
insert into classify(name) values('家电');
insert into classify(name) values('服饰'); --添加users的测试数据
insert into users(name,pwd) values('admin','admin'); --添加商品测试数据
insert into product(name,price,number,c_id) values('arduino基础版',168,50,1);
insert into product(name,price,number,c_id) values('arduino提高版',268,50,1);
insert into product(name,price,number,c_id) values('arduino至尊版',468,50,1);
insert into product(name,price,number,c_id) values('比基尼',68,50,3);
insert into product(name,price,number,c_id) values('虎皮裙',168,50,3);
insert into product(name,price,number,c_id) values('长靴',368,50,3);
insert into product(name,price,number,c_id) values('电冰箱',3268,50,2);
insert into product(name,price,number,c_id) values('烘干机',2268,50,2);
GO select count(*) from users where name='admin' and pwd='admin'
go select count(*) from users where name='xxxdadad' or 1=1 --' and pwd='admin'
go select * from classify;
go
select * from product order by c_id;
go --无返回值
--用途:删除一条记录
CREATE PROCEDURE UP_Product_Delete
@id int
AS
DELETE [product] WHERE id=@id
GO
--用途:修改一条记录
CREATE PROCEDURE UP_Product_Update
@id int,
@name nvarchar(20),
@price decimal(18,0),
@number int,
@c_id int
AS
UPDATE [product] SET
[name]=@name,[price]=@price,[number]=@number,[c_id]=@c_id
WHERE id=@id
GO --有返回值
--用途:增加一条记录
CREATE PROCEDURE UP_Product_ADD
@id int output,--这是返回数据
@name nvarchar(20),
@price decimal(18,0),
@number int,
@c_id int AS
INSERT INTO [product]([name],[price],[number],[c_id])
VALUES(@name,@price,@number,@c_id)
SET @id= @@IDENTITY
GO
--用途:是否已经存在
CREATE PROCEDURE UP_Product_Exist
@id int
AS
DECLARE @TempID int
SELECT @TempID = count(1) FROM [product] WHERE id=@id
IF @TempID = 0
RETURN 0
ELSE
RETURN 1
GO --返回结果集
--用途:得到实体对象的详细信息
CREATE PROCEDURE UP_Product_GetModel
@id int
AS
SELECT id,name,price,number FROM [product] WHERE id = @id
GO --用途:查询记录信息
CREATE PROCEDURE UP_Product_GetList
AS
SELECT id,name,price,number,c_id FROM [Product]
GO --ALTER 更新
--drop 删除
winform代码
Product.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlClient;
using System.Configuration;
using System.Data; namespace ADO.NET.SQL
{
public class Product
{
string connstr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
public Product()
{ } public Product(int _id,string _n,decimal _p,int _num,int _c_id)
{
ID = _id;
Name = _n;
Price = _p;
Number = _num;
C_id = _c_id;
} public int ID
{
get;
set;
} public string Name
{
get;
set;
} public decimal Price
{
get;
set;
} public int Number
{
get;
set;
} public int C_id
{
get;
set;
} /// <summary>
/// 增加一种商品
/// </summary>
/// <param name="_n">名字</param>
/// <param name="_p">价格</param>
/// <param name="_num">库存</param>
/// <param name="_c_id">所属分类</param>
/// <returns>true、false</returns>
public bool Add(string _n, decimal _p, int _num, int _c_id)
{
//using (SqlConnection conn = new SqlConnection(connstr))
//{
// string sql = "insert into product(name,price,number,c_id) values('"+_n+"',"+ _p +","+ _num +","+ _c_id + ")";
// SqlCommand cmd = new SqlCommand(sql, conn); // conn.Open();
// int i = cmd.ExecuteNonQuery();
// if (i > 0)
// return true;
// else
// return false;
//} using (SqlConnection conn = new SqlConnection(connstr))
{
string sql = "UP_Product_ADD";
SqlCommand cmd = new SqlCommand(sql, conn);
cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@name", _n);
cmd.Parameters.AddWithValue("@price", _p);
cmd.Parameters.AddWithValue("@number", _num);
cmd.Parameters.AddWithValue("@c_id", _c_id); SqlParameter pid = new SqlParameter("@id",);
pid.Direction = ParameterDirection.Output;
cmd.Parameters.Add(pid); conn.Open();
int i = cmd.ExecuteNonQuery();
//System.Windows.Forms.MessageBox.Show(cmd.Parameters["@id"].Value.ToString());
if (i > )
return true;
else
return false;
}
} public void Exists(int _id)
{
try
{
using (SqlConnection conn = new SqlConnection(connstr))
{
string sql = "UP_Product_Exist";
SqlCommand cmd = new SqlCommand(sql, conn);
conn.Open();
cmd.CommandType = CommandType.StoredProcedure; SqlParameter pid = new SqlParameter("@id", _id);
pid.Direction = ParameterDirection.Input;
cmd.Parameters.Add(pid); SqlParameter rv = new SqlParameter("@returnvalue", SqlDbType.Int, );
rv.Direction = ParameterDirection.ReturnValue;
cmd.Parameters.Add(rv); int i = cmd.ExecuteNonQuery();
string str1 = cmd.Parameters["@returnvalue"].Value.ToString();
if (str1 == "")
{
System.Windows.Forms.MessageBox.Show("未查到相同的商品ID");
}
else
{
System.Windows.Forms.MessageBox.Show("该商品ID已经存在");
} //if (i > 0)
// return true;
//else
// return false;
}
}
catch (Exception exp)
{
System.Windows.Forms.MessageBox.Show(exp.Message);
}
} /// <summary>
/// 更新一种商品
/// </summary>
/// <param name="_id">id</param>
/// <param name="_n">名字</param>
/// <param name="_p">价格</param>
/// <param name="_num">库存</param>
/// <param name="_c_id">所属分类</param>
/// <returns>true、false</returns>
public bool Update(int _id, string _n, decimal _p, int _num, int _c_id)
{
//using (SqlConnection conn = new SqlConnection(connstr))
//{
// string sql = "UPDATE product SET name='" + _n + "',price = " + _p + ",number=" + _num + ",c_id=" + _c_id + "WHERE id=" + _id;
// SqlCommand cmd = new SqlCommand(sql, conn); // conn.Open();
// int i = cmd.ExecuteNonQuery();
// if (i > 0)
// return true;
// else
// return false;
//} using (SqlConnection conn = new SqlConnection(connstr))
{
string sql = "UP_Product_Update";
SqlCommand cmd = new SqlCommand(sql, conn); cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@id", _id);
cmd.Parameters.AddWithValue("@name", _n);
cmd.Parameters.AddWithValue("@price", _p);
cmd.Parameters.AddWithValue("@number", _num);
cmd.Parameters.AddWithValue("@c_id", _c_id); conn.Open();
int i = cmd.ExecuteNonQuery();
if (i > )
return true;
else
return false;
}
} /// <summary>
/// 移除一个
/// </summary>
/// <param name="_id">id</param>
/// <returns>true、false</returns>
public bool Remove(int _id)
{
//使用SQL语句
//using (SqlConnection conn = new SqlConnection(connstr))
//{
// string sql = "delete from product WHERE id=" + _id;
// SqlCommand cmd = new SqlCommand(sql, conn); // conn.Open();
// int i = cmd.ExecuteNonQuery();
// if (i > 0)
// return true;
// else
// return false;
//} //使用SQL方法
using (SqlConnection conn = new SqlConnection(connstr))
{
string sql = "UP_Product_Delete"; SqlCommand cmd = new SqlCommand(sql, conn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@id", _id); conn.Open();
int i = cmd.ExecuteNonQuery();
if (i > )
return true;
else
return false;
}
} /// <summary>
/// 获取商品列表
/// </summary>
/// <returns>泛型</returns>
public Dictionary<int, Product> GetAll()
{
//Dictionary<int, Product> plist = new Dictionary<int, Product>();
//using (SqlConnection conn = new SqlConnection(connstr))
//{
// string sql = "select * from product";
// SqlCommand cmd = new SqlCommand(sql, conn);
// conn.Open();
// SqlDataReader sdr = cmd.ExecuteReader(System.Data.CommandBehavior.CloseConnection);
// while (sdr.Read())
// {
// Product p = new Product(
// Convert.ToInt32(sdr["id"]),
// sdr["name"].ToString(),
// Convert.ToDecimal(sdr["price"]),
// Convert.ToInt32(sdr["number"]),
// Convert.ToInt32(sdr["c_id"])
// );
// plist.Add(Convert.ToInt32(sdr["id"]), p);
// }
// sdr.Close();
//}
//return plist; Dictionary<int, Product> plist = new Dictionary<int, Product>();
using (SqlConnection conn = new SqlConnection(connstr))
{
string sql = "UP_Product_GetList";
SqlCommand cmd = new SqlCommand(sql, conn); cmd.CommandType = CommandType.StoredProcedure; conn.Open();
SqlDataReader sdr = cmd.ExecuteReader(System.Data.CommandBehavior.CloseConnection);
while (sdr.Read())
{
Product p = new Product(
Convert.ToInt32(sdr["id"]),
sdr["name"].ToString(),
Convert.ToDecimal(sdr["price"]),
Convert.ToInt32(sdr["number"]),
Convert.ToInt32(sdr["c_id"])
);
plist.Add(Convert.ToInt32(sdr["id"]), p);
}
sdr.Close();
}
return plist;
}
}
}
Classify.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlClient;
using System.Configuration; namespace ADO.NET.SQL
{
public class Classify
{
string connstr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString; public int ID
{
get;
set;
} public string Name
{
get;
set;
} /// <summary>
/// 获取所有分类
/// </summary>
/// <returns>分类</returns>
public SqlDataReader GetAll()
{
SqlConnection conn = new SqlConnection(connstr);
SqlCommand cmd = new SqlCommand("select * from classify", conn);
conn.Open();
SqlDataReader sdr = cmd.ExecuteReader(System.Data.CommandBehavior.CloseConnection);
//不推荐
return sdr;
} /// <summary>
/// 通过id获取名字
/// </summary>
/// <param name="cid"></param>
/// <returns></returns>
public string GetCName(int cid)
{
using (SqlConnection conn = new SqlConnection(connstr))
{
SqlCommand cmd = new SqlCommand("select name from classify where id=" + cid.ToString(), conn);
conn.Open();
string str1 = cmd.ExecuteScalar().ToString(); return str1;
}
} /// <summary>
/// 通过名字获取id
/// </summary>
/// <param name="name"></param>
/// <returns></returns>
public int GetCid(string name)
{
using (SqlConnection conn = new SqlConnection(connstr))
{
SqlCommand cmd = new SqlCommand("select id from classify where name=" + name, conn);
conn.Open(); return Convert.ToInt32(cmd.ExecuteScalar());
}
}
}
}
Form1.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.Configuration; namespace ADO.NET.SQL
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
} private void Form1_Load(object sender, EventArgs e)
{
Bind();
} private void Bind()
{
listView1.Items.Clear();
Classify c = new Classify();
Product p = new Product(); ListViewItem lvi;
foreach (Product pr in p.GetAll().Values)
{
lvi = new ListViewItem(pr.ID.ToString());
lvi.SubItems.Add(pr.Name);
lvi.SubItems.Add(pr.Price.ToString());
lvi.SubItems.Add(pr.Number.ToString());
lvi.SubItems.Add(c.GetCName(pr.C_id)); listView1.Items.Add(lvi);
} SqlDataReader sdr = c.GetAll();
while (sdr.Read())
{
comboBox1.Items.Add(sdr[] + "-->" + sdr[]);
}
sdr.Close(); } private void listView1_SelectedIndexChanged(object sender, EventArgs e)
{
if (listView1.SelectedItems.Count != )
{
lbl_id.Text = listView1.SelectedItems[].Text;
tb_name.Text = listView1.SelectedItems[].SubItems[].Text;
tb_price.Text = listView1.SelectedItems[].SubItems[].Text;
tb_number.Text = listView1.SelectedItems[].SubItems[].Text; string cname = listView1.SelectedItems[].SubItems[].Text; for (int i = ; i < comboBox1.Items.Count; i++)
{
int index = comboBox1.Items[i].ToString().IndexOf("-->") + ;//得到箭头结束的位置
if (comboBox1.Items[i].ToString().Substring(index) == cname)
{
comboBox1.SelectedIndex = i;
}
}
}
} /// <summary>
/// 修改
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void button2_Click(object sender, EventArgs e)
{
try
{ int id = int.Parse(lbl_id.Text); int index = comboBox1.Text.IndexOf("-->");
int cid = int.Parse(comboBox1.Text.Substring(, index)); Product p = new Product();
if (
p.Update
(
id,
tb_name.Text,
decimal.Parse(tb_price.Text),
int.Parse(tb_number.Text),
cid
)
)
{
Bind();
}
else
{
MessageBox.Show("没修改成功哦!");
}
}
catch (Exception exp)
{
MessageBox.Show(exp.Message);
}
} /// <summary>
/// 添加
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void button3_Click(object sender, EventArgs e)
{
try
{
Product p = new Product(); int index = comboBox1.Text.IndexOf("-->");
int cid = int.Parse(comboBox1.Text.Substring(, index)); if (
p.Add
(
tb_name.Text,
decimal.Parse(tb_price.Text),
int.Parse(tb_number.Text),
cid
)
)
{
Bind();
}
else
{
MessageBox.Show("没添加成功哦!");
}
}
catch(Exception exp)
{
MessageBox.Show(exp.Message);
}
} /// <summary>
/// 删除商品
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void button1_Click(object sender, EventArgs e)
{
try
{
int id = int.Parse(lbl_id.Text);
Product p = new Product();
if (
p.Remove(id)
)
{
Bind();
}
else
{
MessageBox.Show("没删除成功哦!");
}
}
catch (Exception exp)
{
MessageBox.Show(exp.Message);
}
} private void button6_Click(object sender, EventArgs e)
{
try
{
Product p = new Product();
p.Exists(int.Parse(tb_Exist.Text));
}
catch (Exception exp)
{
MessageBox.Show(exp.Message);
}
}
}
}
app.config
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<connectionStrings>
<add name="constr" connectionString="server=QT-201303030913;database=ThreeDb;uid=sa;pwd=*******"/>
</connectionStrings>
</configuration>
C#练习DataReader的更多相关文章
- 报错:已有打开的与此命令相关联的 DataReader,必须首先将它关闭。
SqlParameter[] sp = { new SqlParameter("@nGridID",SqlDbType.BigInt), new SqlParameter(&quo ...
- DataReader
Datareader对象不能关使用new关键字创建.但可以使用ExecuteReader()方法创建. DataReader是一行一行的读取记录的.当记录中有数据时Read()返回TRUE,当到记录集 ...
- code first提示已有打开的与此 Command 相关联的 DataReader,必须首先将它关闭解决方法
使用codefirst查询当然是必不可少的,但有时不小心可能很简单的查询也会导致异常. 下面用codefirst做个示例简单演示下异常发生的场景: var attendlist = db.Databa ...
- 将DataReader转换为DataTable
public static DataTable ConvertDataReaderToDataTable(SqlDataReader dataReader) { ///定义DataTable Data ...
- C# 之 DataReader 和 DataSet 的区别
本文转载自:http://www.cnblogs.com/xinaixia/p/4920630.html 1. 获取数据的方式[1]DataReader 为在线操作数据, DataReader会一直占 ...
- C#中对象,字符串,dataTable、DataReader、DataSet,对象集合转换成Json字符串方法。
C#中对象,字符串,dataTable.DataReader.DataSet,对象集合转换成Json字符串方法. public class ConvertJson { #region 私有方法 /// ...
- 【2016-11-2】【坚持学习】【Day17】【通过反射自动将datareader转为实体info】
通过ADO.net 查询到数据库的数据后,通过DataReader转为对象Info public class BaseInfo { /// <summary> /// 填充实体 /// & ...
- 原创 Datareader 导出为csv文件方法
DataReader 是游标只读数据, 如果是大数据导出,用Datatable 将耗费巨大内存资源.因为Datatable 其实就是内存中的一个数据表 代码如下 /// <summary> ...
- DataReader用法
一.DataReader含义 DataReader相比于DataSet,DataReader是一个抽象类,所以不能用DataReader DR = new DataReader(),来构造函数创建对象 ...
- DataReader和DataSet的异同
DataReader:使用时始终占用SqlConnection,在线操作数据库:每次只在内存中加载一条数据,所以占用的内存是很小的:是只进的. 只读的. DataSet:则是将数据一次性加载在内存中. ...
随机推荐
- 通知传值(NSNotificationCenter)
watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvenVveW91MTMxNA==/font/5a6L5L2T/fontsize/400/fill/I0JBQk ...
- js 参数校验器
//校验器 var validate = { //校验当前运行环境是否是手机端 isWap:function(){ var sUserAgent= navigator.userAgent.toLowe ...
- hdu4888 多校B 最大流以及最大流唯一推断+输出方案
题意.给一个矩阵,告诉你每行和.每列和.而且限制所填数不大于k,问矩阵是否唯一. 经典建图不说了.第一次遇到推断最大流唯一性的.学习了:用dfs来推断残网中是否还存在环,若存在,则表明绕这个环走一圈, ...
- discuz !NT 3.5 论坛整合 .net 网站用户登录,退出
using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.HtmlCont ...
- 会话管理之session技术
上一节我们总结了cookie技术,这节主要总结一下session技术. 1. session对象 在web开发中,服务器可以为每个用户浏览器创建一个会话对象(session对象),注意:一个浏览器独占 ...
- Socket 异步通信示例
这个项目是一个控制台应用程序: 服务器端: using System; using System.Net; using System.Net.Sockets; using System.Text; u ...
- ASP.NET中的配置文件
ASP.NET中的配置文件 原创 2014年10月13日 08:15:27 1199 在机房收费系统的时候曾经应用过配置文件,当时也就那么一用对配置文件了解的不是很透彻,下面就来总结一下有关配置文 ...
- Atitit.程序包装exe启动器 打包 发布 设计 -生成exe java
Atitit.程序包装exe启动器 打包 发布 设计 -生成exe java 1. 要实现的功能1 2. ahk是个好东东..能启动了...1 3. exe4j vs nativej1 4. 2 ...
- Weka学习之认识weka(一)
Weka 简介 WEKA作为一个公开的数据挖掘工作平台,集合了大量能承担数据挖掘任务的机器学习算法,包括对数据进行预处理,分类,回归.聚类.关联规则以及在新的交互式界面上的可视化. Weka是基 ...
- C分配struct变量一个不理解的地方