练习题:
1、Car表数据查出显示
2、请输入要查的汽车名称:输入可以为空。
请输入要查的汽车油耗:输入可以为空。
请输入要查的汽车马力:输入可以为空。
1 SqlConnection a = new SqlConnection("server=.;database=ADOlianxi0425;user=sa;pwd=123;"); 2 SqlCommand b = a.CreateCommand(); 3 string MC = ""; 4 string YH = ""; 5 decimal YH1; 6 string ML = ""; 7 int ML1; 8 for (; ; ) 9 { 10 //输入想要查询的车名称油耗以及马力 11 for (; ; ) 12 { 13 Console.Write("请输入汽车名称:"); 14 MC = Console.ReadLine(); 15 if (MC == "") 16 { 17 break; 18 } 19 b.CommandText = "select * from car where name like @MC"; 20 b.Parameters.Clear(); 21 b.Parameters.Add("@MC", "%" + MC + "%"); 22 a.Open(); 23 SqlDataReader c = b.ExecuteReader(); 24 if (c.HasRows) 25 { 26 a.Close(); 27 break; 28 } 29 else 30 { 31 a.Close(); 32 Console.WriteLine("没有这种汽车!请重新输入!"); 33 } 34 } 35 for (; ; ) 36 { 37 Console.Write("请输入汽车油耗:"); 38 YH = Console.ReadLine(); 39 if (YH == "") 40 { 41 break; 42 } 43 try 44 { 45 YH1 = Convert.ToDecimal(YH); 46 b.CommandText = "select * from car where oil like @YH"; 47 b.Parameters.Clear(); 48 b.Parameters.Add("@YH", "%" + YH1 + "%"); 49 a.Open(); 50 SqlDataReader c = b.ExecuteReader(); 51 if (c.HasRows) 52 { 53 a.Close(); 54 break; 55 } 56 else 57 { 58 a.Close(); 59 Console.WriteLine("没有这种油耗!请重新输入!"); 60 } 61 } 62 catch 63 { 64 Console.WriteLine("输入错误请重新输入!"); 65 } 66 } 67 for (; ; ) 68 { 69 Console.Write("请输入汽车马力:"); 70 ML = Console.ReadLine(); 71 if (ML == "") 72 { 73 break; 74 } 75 try 76 { 77 ML1 = Convert.ToInt32(ML); 78 b.CommandText = "select * from car where powers like @ML"; 79 b.Parameters.Clear(); 80 b.Parameters.Add("@ML", "%" + ML1 + "%"); 81 a.Open(); 82 SqlDataReader c = b.ExecuteReader(); 83 if (c.HasRows) 84 { 85 a.Close(); 86 break; 87 } 88 else 89 { 90 a.Close(); 91 Console.WriteLine("没有这种马力!请重新输入!"); 92 } 93 } 94 catch 95 { 96 Console.WriteLine("输入错误请重新输入!"); 97 } 98 } 99 //按照用户输入编写SQL语句 100 b.CommandText = "select * from car where name like @MC1 and oil like @YH1 and powers like @ML1"; 101 b.Parameters.Clear(); 102 b.Parameters.Add("@MC1", "%" + MC + "%"); 103 b.Parameters.Add("@YH1", "%" + YH + "%"); 104 b.Parameters.Add("@ML1", "%" + ML + "%"); 105 //查询打印 106 a.Open(); 107 SqlDataReader c1 = b.ExecuteReader(); 108 if (c1.HasRows) 109 { 110 while (c1.Read()) 111 { 112 Console.WriteLine("车名:" + c1["name"] + " 油耗:" + c1["oil"] + " 马力:" + c1["powers"] + " 价格:" + c1["price"]); 113 } 114 } 115 else 116 { 117 Console.WriteLine("没有符合条件的车!"); 118 } 119 a.Close(); 120 Console.Write("是否结束查询:"); 121 string HAHAHA = Console.ReadLine(); 122 if (HAHAHA == "是") 123 { 124 Console.Clear(); 125 Console.Write("-----------------------------------谢谢使用------------------------------------"); 126 break; 127 } 128 Console.Clear(); 129 }