public enum Sex
{
Male = 0,
Female
}
public class Customer
{
int? nID;
string firstName;
string lastName;
Sex sex;
string interest;
public Customer(int? nID, string firstName, string lastName, Sex sex, string interest)
{
this.nID = nID;
this.firstName = firstName;
this.lastName = lastName;
this.sex = sex;
this.interest = interest;
}
public Sex Sex
{
get { return sex; }
set { sex = value; }
}
public int? NID
{
get { return nID; }
set { nID = value; }
}
public string FirstName
{
get { return firstName; }
set { firstName = value; }
}
public string LastName
{
get { return lastName; }
set { lastName = value; }
}
public string Interest
{
get { return interest; }
set { interest = value; }
}
}
public class CustomerData
{
const string MSSQLConnectionString = "Data Source=.;Initial Catalog=test;User ID=sa;Password=123456";
const string SqlInsertString = "Insert into tbCustomer (firstName,lastName,sex,interest) values (@firstName,@lastName,@sex,@interest)";
const string SqlSelectAllStrig = "select *from tbCustomer";
public void Insert(Customer customer)
{
SqlConnection con = new SqlConnection(MSSQLConnectionString);
con.Open();
SqlCommand cmd = new SqlCommand(SqlInsertString, con);
cmd.Parameters.AddWithValue("@firstName",customer.FirstName);
cmd.Parameters.AddWithValue("@lastName", customer.LastName);
cmd.Parameters.AddWithValue("@sex", customer.Sex);
cmd.Parameters.AddWithValue("@interest", customer.Interest);
cmd.ExecuteNonQuery();
con.Close();
}
public IList<Customer> GetAll()
{
SqlConnection con = new SqlConnection(MSSQLConnectionString);
SqlCommand command = new SqlCommand(SqlSelectAllStrig, con);
DataSet ds = new DataSet();
SqlDataAdapter da = new SqlDataAdapter(command);
da.Fill(ds);
DataTable dt = new DataTable();
dt = ds.Tables[0];
IList<Customer> customers = new List<Customer>();
foreach (DataRow row in dt.Rows)
{
Customer customer = new Customer(Convert.ToInt32(row["nID"]), row["firstName"].ToString(), row["lastName"].ToString(),(Sex)Convert.ToInt32(row["sex"]), row["interest"].ToString());
customers.Add(customer);
}
return customers;
}
}
class Program
{
static void Main(string[] args)
{
//Customer customer = new Customer(null, "viper", "Tang", Sex.Male, "Playing BasketBall");
CustomerData cd = new CustomerData();
//cd.Insert(customer);
foreach (var item in cd.GetAll())
{
Console.WriteLine(item.NID + " " + item.FirstName + item.LastName + " " + item.Sex + " " + item.Interest);
}
Console.ReadKey();
}
}
插入枚举值:Sex.Male到数据库时,插入的是值0,初始化Customer时赋0值给枚举字段属性Sex,读出来时就对应上Male.