--SQl中
--建立ren的數據庫,插入一條信息 create database ren go use ren go create table xinxi ( code nvarchar(20) primary key,--編號 name nvarchar(20)--名字 ) insert into xinxi values('1001','zhangsan')
在上一遍操作中,有一個BUG,在操作“刪改”時,如果用戶輸錯了編號,沒有提醒,那么就先要進行查詢是否有這個編號的信息,然后再進行操作
//C#中
//修改 for (; ; ) { //先查詢是否有這么一個數據,如果有,進行操作;如果沒有,重新輸入,知道輸入正確為止!! bool b = false;//利用中間變量 Console.Write("請輸入要修改的編號:"); string no = Console.ReadLine(); //查詢展示 SqlConnection zhancnn = new SqlConnection("server=.;database=ren;user=sa;pwd=123");//連接 //操作的語句 SqlCommand zhancmd = zhancnn.CreateCommand(); zhancmd.CommandText = "select * from xinxi where code='" + no + "'"; //執行操作的語句 zhancnn.Open(); SqlDataReader ss = zhancmd.ExecuteReader(); if (ss.HasRows)//數據庫中是否有要修改的數據,有沒有行。 { b = true; } zhancnn.Close(); if (b == true)//如果有要修改的數據 { Console.WriteLine("找到【" + no + "】的信息,是否確定要修改?Y/N"); if (Console.ReadLine().ToUpper() == "Y")//確定修改 { Console.Write("請輸入要修改的名字:"); string mingzi = Console.ReadLine(); zhancmd.CommandText = "update xinxi set name='" + mingzi + "' where code='" + no + "'";//由於上面已經實例化,所以不用重新實例化,注意open和close zhancnn.Open(); zhancmd.ExecuteNonQuery(); zhancnn.Close(); Console.WriteLine("編號為" + no + "的信息修改成功!"); } else//不修改 { } break; } else//如果沒有要修改的數據 { Console.WriteLine("數據庫中沒有該條信息,請輸入正確的編碼!!"); } } Console.ReadLine();
修改和刪除的格式一樣,就是執行語句不一樣!!
