unity学习之增删查改

来源:互联网 发布:怎么注册网络直播公司 编辑:程序博客网 时间:2024/05/16 12:32

unity学习,希望我的博客能给正在学习unity的朋友们带来帮助


今天我们来学习在vs中对数据库中的数据进行增删查改,直接来看代码吧


封装,方便方法的使用
  1. class Users
  2.     {
  3.         private int id;
  4.         public int Id
  5.         {
  6.             get { return id; }
  7.             set { id = value; }
  8.         }
  9.         private string name;
  10.         public string Name
  11.         {
  12.             get { return name; }
  13.             set { name = value; }
  14.         }
  15.     }

方法
  1. class Program
  2.     {
  3.         List<Users> list = new List<Users>();
  4.         public List<Users> select() {
  5.             SqlConnection con = new SqlConnection("server=.;database=GameMarket;Trusted_Connection=SSPI");
  6.             con.Open();
  7.             string sql = "select * from users";
  8.             SqlCommand sc = new SqlCommand(sql, con);
  9.             SqlDataReader reader = sc.ExecuteReader();
  10.             while (reader.Read()) {
  11.                 Users u = new Users();
  12.                 u.Id =(int) reader.GetValue(0);
  13.                 u.Name = (string)reader.GetValue(1);

  14.                 list.Add(u);
  15.             }
  16.             return list;
  17.         }

  18.         public int insert(string name)
  19.         {
  20.             SqlConnection con = new SqlConnection("server=.;database=GameMarket;Trusted_Connection=SSPI");
  21.             con.Open();
  22.             string sql = "insert into users values('"+name+"')";
  23.             SqlCommand sc = new SqlCommand(sql, con);
  24.             int i=sc.ExecuteNonQuery();
  25.             return i;
  26.         }

  27.         public int update(int id,string name)
  28.         {
  29.             SqlConnection con = new SqlConnection("server=.;database=GameMarket;Trusted_Connection=SSPI");
  30.             con.Open();
  31.             string sql = "update users set name='"+name+"' where id="+id+"";
  32.             SqlCommand sc = new SqlCommand(sql, con);
  33.             int i = sc.ExecuteNonQuery();
  34.             return i;
  35.         }

  36.         public int delete(int id)
  37.         {
  38.             SqlConnection con = new SqlConnection("server=.;database=GameMarket;Trusted_Connection=SSPI");
  39.             con.Open();
  40.             string sql = "delete from users where id="+id+"";
  41.             SqlCommand sc = new SqlCommand(sql, con);
  42.             int i = sc.ExecuteNonQuery();
  43.             return i;
  44.         }

当然千万不要忘了using引用:
using System.Data;
using System.Data.SqlClient;

更多精彩请点击 http://www.gopedu.com/article


0 0