您的位置:首页 > 数据库

使用c#进行数据库的查看增加修改删除数据

2014-12-16 20:55 706 查看
欢迎来到unity学习unity培训

这里有很多U3D资源U3D培训视频、U3D教程、U3D常见问题、U3D项目源码,我们致力于打造业内unity3d培训、学习第一品牌

1、想要在c#里面调用数据库首先需要两个引用集



using System.Data;

using System.Data.SqlClient;

2、查询

List<Users> list = new List<Users>();

        public List<Users> select() {

            SqlConnection con = new SqlConnection("server=.;database=GameMarket;Trusted_Connection=SSPI");//连接数据库创建对象

            con.Open();//打开数据库

                         //创建执行对象及SQL语句

            string sql = "select * from users";//要执行的SQL语句

            SqlCommand sc = new SqlCommand(sql, con);

                        //创建数据读取对象,循环读取数据

            SqlDataReader reader = sc.ExecuteReader();

            while (reader.Read()) {

                Users u = new Users();

                u.Id =(int) reader.GetValue(0);

                u.Name = (string)reader.GetValue(1);

                list.Add(u);

            }

            return list;//因为方法类型是list类型,所以要返回值

                        
//如果不需要数据库要关闭,con.Close();

        }

3、插入

public int insert(string name)

        {

                        
//简介数据库创建对象

            SqlConnection con = new SqlConnection("server=.;database=GameMarket;Trusted_Connection=SSPI");

            con.Open();//打开数据库

                        
//创建数据读取对象

            string sql = "insert into users values('"+name+"')";//要执行的SQL语句

            SqlCommand sc = new SqlCommand(sql, con);

            int i=sc.ExecuteNonQuery();

            return i;

        }

4、修改

 public int update(int id,string name)

        {

                        
//基本和添加数据一样,就是写要执行的SQL语句时不一样,添加是添加语句,而修改时修改语句

            SqlConnection con = new SqlConnection("server=.;database=GameMarket;Trusted_Connection=SSPI");

            con.Open();

            string sql = "update users set name='"+name+"' where id="+id+"";//要执行的SQL语句

            SqlCommand sc = new SqlCommand(sql, con);

            int i = sc.ExecuteNonQuery();

            return i;

        }

5、删除

public int delete(int id)

        {

            //这个写的是删除语句

            SqlConnection con = new SqlConnection("server=.;database=GameMarket;Trusted_Connection=SSPI");

            con.Open();

            string sql = "delete from users where id="+id+"";//要执行的语句

            SqlCommand sc = new SqlCommand(sql, con);

            int i = sc.ExecuteNonQuery();

            return i;

        }
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
相关文章推荐