using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.SqlClient;
namespace ConsoleApplication1
{
//主要实现对Nation表的各种操作(增删改查)
public class NationDA
{
private SqlConnection _conn; //连接对象
private SqlCommand _cmd; //命令对象
private SqlDataReader _dr; //读取器对象
//构造方法来初始化连接对象 命令对象
public NationDA()
{
_conn = DBConnect.Conn; //对连接对象进行初始化
_cmd = _conn.CreateCommand(); //对命令对象进行初始化
}
//添加数据的方法
public bool Add(string code,string name)
{
_cmd.CommandText = "insert into Nation values(@code,@name)";
_cmd.Parameters.AddWithValue("@code",code);
_cmd.Parameters.AddWithValue("@name",name);
_conn.Open();
int n = _cmd.ExecuteNonQuery();
if (n > 0)
{
return true;
}
else
{
return false;
}
}
//查询所有数据的方法
public List<Nation> Select()
{
_cmd.CommandText = "select * from Nation";
_conn.Open();
_dr = _cmd.ExecuteReader();
_conn.Close();
//定义一个空的集合
List<Nation> list = new List<Nation>();
if (_dr.HasRows)
{
while (_dr.Read())
{
//造一个Nation对象
Nation data = new Nation();
data.Code = _dr[0].ToString();
data.Name = _dr[1].ToString();
//扔到集合里面
list.Add(data);
}
}
_conn.Close();
return list;
}
}
}