C#与数据库链接---小练4--删除语句
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data;
using System.Data.SqlClient;
namespace ConsoleApplication2
{
class Shanchuyuju
{
public const string AB = "server=.;database=wo0505;uid=sa;pwd=123";
public static void Main222(string[] args)
{
Show();
Shanchu();
Show();
Console.ReadLine();
}//主函数,进行各部分主要功能的调用
public static void Show()
{
SqlConnection con = new SqlConnection(AB);
con.Open();
SqlCommand cmd = con.CreateCommand();
cmd.CommandText = "select * from Info";
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
string aa = dr["Code"].ToString();
string bb = dr["Name"].ToString();
string cc = ((bool)dr["Sex"]) ? "男" : "女";
string dd = dr["Nation"].ToString();
string ee = ((DateTime)dr["Birthday"]).ToString("yyyy年MM月dd日");
Console.WriteLine(aa + "\t" + bb + "\t" + cc + "\t" + dd + "\t" + ee);
}
con.Close();
}//显示所要删除数据的表中的所有数据
public static void Shanchu()
{
Console.WriteLine("请输入要删除的数据行的编号:");
string bianhao=Console.ReadLine();
string yan = Yanz(bianhao);
if (yan == "you")
{
Shan(bianhao);
Console.WriteLine("已删除!");
}
else
{
Console.WriteLine("您输入的编号不存在,请重新输入!");
}
}//删除,输入要删除的一行数据的编号(或其他列名,可改)
public static string Yanz(string b)
{
string ok = "you";
SqlConnection con = new SqlConnection(AB);
con.Open();
SqlCommand cmd = con.CreateCommand();
cmd.CommandText = "select * from Info";
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
if (dr["Code"].ToString() == b)
{ ok = "you"; break; }
else { ok = "bu"; }
}
con.Close();
return ok;
}//验证输入的要删除行数的编号是否已存在,
public static void Shan(string bi)
{
SqlConnection con = new SqlConnection(AB);
con.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandText = "delete from Family where InfoCode='"+bi+"'";
cmd.ExecuteNonQuery();
cmd.CommandText = "delete from Work where InfoCode='"+bi+"'";
cmd.ExecuteNonQuery();
cmd.CommandText = "delete from Info where Code='"+bi+"'";
cmd.ExecuteNonQuery();
con.Close();
}
//删除已存在的数据,并关注该行数据以主键为主的“其他表中的关联数据”也一并删除
}//简单的删除数据表中的数据
}