標籤:username span false [] tar bre select ado.net 迴圈
using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Data.SqlClient;namespace ConsoleApplication2{ class Program { static void Main(string[] args) { //刪除 //建立資料庫連接對象,並編寫連接字串,注意連接字串不要寫錯 SqlConnection conn = new SqlConnection("server=.;database=Data0928;user=sa;pwd=123"); //建立資料庫操作對象,建立過程是與剛建立的連線物件匹配起來 SqlCommand cmd = conn.CreateCommand(); Console.Write("請輸入想要刪除的使用者名稱:"); string user = Console.ReadLine(); //編寫動作陳述式 TSQL語句 cmd.CommandText = "select ids,UserName,PassWord,NickName,Sex,Birthday,(select NationName from Nation where NationCode=Users.Nation) as ‘Nation‘ ,ClassName as ‘Class‘ from Users join Class on Class.ClassCode=Users.Class where UserName=‘"+user+"‘"; //資料庫連接開啟,準備執行操作 conn.Open(); SqlDataReader dr = cmd.ExecuteReader();//使用SqlDataReader類接受查詢的資料 if (dr.HasRows)//判斷dr裡是否有資料 返回布爾類型 { while(dr.Read())//迴圈每一行 當超出時返回false { Console.WriteLine(dr["ids"]+"\t"+dr["UserName"]+"\t"+dr["PassWord"]+"\t"+dr["NickName"]+"\t"+(Convert.ToBoolean(dr["Sex"])?"男":"女")+"\t"+Convert.ToDateTime(dr["Birthday"]).ToString("yyyy年MM月dd日")+"\t"+dr["Nation"]+"\t"+dr["Class"]); } //關閉資料庫連接 conn.Close(); Console.Write("是否確定刪除此條資料?(Y/N)"); string yn = Console.ReadLine(); if (yn == "y") { cmd.CommandText = "delete from Users where UserName=‘"+user+"‘"; conn.Open(); int i = cmd.ExecuteNonQuery();//執行操作,並記錄受影響的行數 if (i > 0) Console.WriteLine("刪除成功。"); else { Console.WriteLine("刪除失敗"); } conn.Close(); } else if (yn == "n") { Console.WriteLine("取消刪除。"); } else { Console.WriteLine("輸入有誤!"); } } else { Console.WriteLine("查無此條資料!"); } conn.Close(); //添加 Console.Write("請輸入想要添加的使用者名稱:"); string uname = Console.ReadLine(); cmd.CommandText = "select * from Users"; conn.Open(); dr = cmd.ExecuteReader(); int biao = 0; //查詢使用者名稱是否重複 if(dr.HasRows) { while(dr.Read()) { if(dr["UserName"].ToString()==uname) { biao++; break; } } } conn.Close(); if (biao == 0)//使用者名稱無重複 { Console.Write("請輸入密碼:"); string pwd = Console.ReadLine(); Console.Write("請輸入暱稱:"); string nick = Console.ReadLine(); Console.Write("請輸入性別:"); string sex = Console.ReadLine(); Console.Write("請輸入生日:"); string bir = Console.ReadLine(); Console.Write("請輸入民族:"); string nation = Console.ReadLine(); Console.Write("請輸入班級:"); string cla = Console.ReadLine(); cmd.CommandText = "insert into Users values(‘" + uname + "‘,‘" + pwd + "‘,‘" + nick + "‘,‘" + sex + "‘,‘" + bir + "‘,‘" + nation + "‘,‘" + cla + "‘)"; conn.Open(); int s = cmd.ExecuteNonQuery(); if (s > 0) { Console.WriteLine("添加成功!"); } else { Console.WriteLine("添加失敗!"); } conn.Close(); } else//使用者名稱重複 { Console.WriteLine("該使用者名稱已存在!"); } Console.ReadKey(); } }}
ado.net增刪改查練習