练习: //1.让用户输入一个代号,查到一条数据(car,info),并显示 //2.输出提示:输入1删除该数据 输入2修改数据 输入3添加数据 //3.当用户输入1的话:把查到的这条数据删除 //4.当用户输入2的话:让用户输入修改的其它值,输入完成修改这条数据 //5.当用户输入3的话:让用户输入所有的列,然后保存到数据库 Console.WriteLine("请输入一个代号:"); string code = Console.ReadLine(); SqlConnection conn = new SqlConnection("server=.;database=mydb;user=sa;pwd=yue801828"); SqlCommand cmd = conn.CreateCommand(); cmd.CommandText = "select * from Car where Code=@code"; cmd.Parameters.Clear(); cmd.Parameters.AddWithValue("@code", code); conn.Open(); SqlDataReader dr = cmd.ExecuteReader(); if (dr.HasRows) { while (dr.Read()) { Console.WriteLine(dr[0] + "--" + dr[1]); Console.WriteLine("输入1删除该数据 , 输入2修改数据,输入3添加数据"); } int a = int.Parse(Console.ReadLine()); dr.Close(); if (a == 1) { cmd.CommandText = "delete from car where Code=@code"; cmd.ExecuteNonQuery(); Console.WriteLine("删除成功!"); } else if (a == 2) { Console.WriteLine("请输入您要修改的数据:"); string name = Console.ReadLine(); cmd.Parameters.Clear(); cmd.Parameters.AddWithValue("@code", code); cmd.Parameters.AddWithValue("@name", name); cmd.CommandText = "update car set name=@name where code=@code"; cmd.ExecuteNonQuery(); Console.WriteLine("修改成功!"); } else if (a == 3) { Console.WriteLine("请输入内容:"); Console.WriteLine("请输入代号"); string Code = Console.ReadLine(); Console.WriteLine("请输入名称:"); string Name = Console.ReadLine(); Console.WriteLine("请输入系列名:"); string Brand = Console.ReadLine(); Console.WriteLine("请输入日期"); string time = Console.ReadLine(); Console.WriteLine("请输入内容油耗*.**"); double oil = double.Parse(Console.ReadLine()); Console.WriteLine("请输入内容马力"); int powers = int.Parse(Console.ReadLine()); Console.WriteLine("请输入内容"); int exhaust = int.Parse(Console.ReadLine()); Console.WriteLine("请输入内容"); double price = double.Parse(Console.ReadLine()); Console.WriteLine("请输入内容"); string pic = Console.ReadLine(); cmd.CommandText = "insert into car values( @code,@name,@brand,@time,@oil,@powers,@exhaust,@price,@pic)"; cmd.Parameters.Clear(); cmd.Parameters.AddWithValue("@code", code2); cmd.Parameters.AddWithValue("@name", name); cmd.Parameters.AddWithValue("@brand", brand); cmd.Parameters.AddWithValue("@time", time); cmd.Parameters.AddWithValue("@oil", oil); cmd.Parameters.AddWithValue("@powers", powers); cmd.Parameters.AddWithValue("@exhaust", exhaust); cmd.Parameters.AddWithValue("@price", price); cmd.Parameters.AddWithValue("@pic", pic); cmd.ExecuteNonQuery(); Console.WriteLine("添加成功!"); } else { Console.WriteLine("输入有误"); } } else { Console.WriteLine("没有查到相应的数据"); } conn.Close(); Console.ReadLine(); } } }