.NET SQLserver插入数据

用C#语言向数据库中插数据并不是像Java一样需要占位符,而是严格按照Sql语句进行转化,并插入变量。详细解析请看这里 http://www.ihongguang.cn/?p=33

不说废话,直接看代码,以下为WebApi实例代码

     public bool PostRegister([FromBody]Member member)
     {
         member.sex = (member.sex == "male" ? "true" : "false");
         if (member.rank == "Root")
             rankNumber = 1;
         else
             if (member.rank == "Monitor")
                 rankNumber = 2;
             else
         rankNumber = 3;
         try
         {
             SqlConnection conn = connectLocaldb.ConnectDataBase();
             conn.Open();
             string sql = "INSERT INTO Member(username,password,sex,rank) VALUES ('" + member.username + "','" + member.username + "'+'_123','" + member.sex + "',"+ rankNumber + ")";
             SqlCommand cmd = new SqlCommand(sql, conn);
             int result = cmd.ExecuteNonQuery();
             conn.Close();
             flag = true;
         }
         catch(SqlException e)
         {
             flag = false;
         }
         return flag;
     } 
文章目录
|