ADO.NET完整增添删除防御

//让用户输入信息
string ucode = "";

//开始 生成编号

SqlConnection conn = new SqlConnection("server=.;database=Data0504;user=sa;pwd=123;");
SqlCommand cmd = conn.CreateCommand();
cmd.CommandText = "select * from Users order by Ucode desc";
conn.Open();
SqlDataReader dr = cmd.ExecuteReader();
dr.Read();
ucode = dr["Ucode"].ToString();

int a = Convert.ToInt32(ucode.Substring(1));
a++;
ucode = "U" + a.ToString("000");

conn.Close();

//结束 生成编号

Console.WriteLine("您的编号是:" + ucode);
Console.Write("请输入用户名:");
string username = Console.ReadLine();
Console.Write("请输入密码:");
string password = Console.ReadLine();
Console.Write("请输入昵称:");
string nickname = Console.ReadLine();
Console.Write("请输入性别:");
string sex = Console.ReadLine();
Console.Write("请输入生日:");
string birthday = Console.ReadLine();
Console.Write("请输入民族:");
string nation = Console.ReadLine();

//添加到数据库中去
conn.Open();
cmd.CommandText = "insert into Users values(@a,@b,@c,@d,@e,@f,@g)";
cmd.Parameters.Clear();
cmd.Parameters.AddWithValue("@a", ucode);
cmd.Parameters.AddWithValue("@b", username);
cmd.Parameters.AddWithValue("@c", password);
cmd.Parameters.AddWithValue("@d", nickname);
cmd.Parameters.AddWithValue("@e", sex);
cmd.Parameters.AddWithValue("@f", birthday);
cmd.Parameters.AddWithValue("@g", nation);

int count = cmd.ExecuteNonQuery();

conn.Close();
if (count > 0) Console.WriteLine("添加成功");
else Console.WriteLine("失败!");

Console.ReadLine();

 

bool has = false;
Console.Write("请输入要删除的编号:");
string ucode = Console.ReadLine();

//先查询有无此数据
SqlConnection conn = new SqlConnection("server=.;database=Data0504;user=sa;pwd=123;");
SqlCommand cmd = conn.CreateCommand();

cmd.CommandText = "select *from Users where Ucode=@a";
cmd.Parameters.Clear();
cmd.Parameters.AddWithValue("@a", ucode);

conn.Open();
SqlDataReader dr = cmd.ExecuteReader();
if (dr.HasRows)
{
has = true;
}
conn.Close();

if (has)
{
cmd.CommandText = "delete from Users where Ucode=@a ";
cmd.Parameters.Clear();
cmd.Parameters.AddWithValue("@a", ucode);
conn.Open();
int count = cmd.ExecuteNonQuery();

conn.Close();

if (count > 0)
{
Console.WriteLine("删除成功!");

}
else
{
Console.WriteLine("删除失败!");

}

}
else
{
Console.WriteLine("您输入的编号不正确,请重新输入!");

}

 


Console.ReadLine();

 

posted @ 2017-07-06 20:41  零语言  阅读(89)  评论(0编辑  收藏  举报