1.使用命令参数:
cmd.CommandText = "[email protected] ....";
cmd.Parameters.Clear();
cmd.Parameters.AddWithValue("@uid","值")
cmd.ExecuteXXXXX();
2.ExecuteScalar()执行SQL语句,返回首行首列中的值。
它一般用来执行聚合函数的查询。
3.事务Transaction
ACID - A原子性。C一致性。I-隔离性。D持久性。
两类事务:
(一)链接内事务:在链接打开后,使用事务控制多条语句的执行。
1.创建事务对象。
SqlTransanction trans = conn.BeginTransaction(); //注意必须是链接打开后编写
2.把事务对象挂到命令对象上,让命令执行带有事务的功能。
cmd.Transaction = trans;
3.按照之前所讲得执行命令操作数据库
a.成功后调用事务对象的Commit()方法来提交执行的结果。
b.失败后调用事务对象的Rollback()方法来回滚执行前的状态。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data;
using System.Data.SqlClient;
namespace lian_CommandBehavior
{
class lian_shiwu
{
public const string AB = "server=.;database=wo0505;uid=sa;pwd=123";
public static void Main11(string[] args)
{
Show();
Shanchu();
Show();
Console.ReadLine();
}
public static void Shanchu()//删除相应的有外键的信息
{
Console.Write("请输入需要删除的人员的编号");
string co = Console.ReadLine();
string ok = "";
ok = Yancode(co);
if (ok == "cun")
{
SqlConnection con = new SqlConnection(AB);
try
{
con.Open();
SqlCommand cmd = con.CreateCommand();
SqlTransaction tran = con.BeginTransaction();
cmd.Transaction = tran;
try
{
cmd.CommandText = "delete from Family where [email protected]";
cmd.Parameters.Clear();
cmd.Parameters.AddWithValue("@c", co);
cmd.ExecuteNonQuery();
cmd.CommandText = "delete from Work where [email protected]";
cmd.Parameters.Clear();
cmd.Parameters.AddWithValue("@c", co);
cmd.ExecuteNonQuery();
cmd.CommandText = "delete from Info where [email protected]";
cmd.Parameters.Clear();
cmd.Parameters.AddWithValue("@c", co);
cmd.ExecuteNonQuery();
tran.Commit();
}
catch
{
Console.WriteLine("删除未成功,返回执行前的数据!");
tran.Rollback();
}
}
catch
{
Console.WriteLine("未删除!");
}
finally
{
con.Close();
}
}
else { Console.WriteLine("您输入的编号不存在!"); }
}
public static string Yancode(string code)//验证是否存在相应的信息
{
string ok = "cun";
SqlConnection con = new SqlConnection(AB);
try
{
con.Open();
SqlCommand cmd = con.CreateCommand();
cmd.CommandText = "select * from Info";
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
if(dr["Code"].ToString()==code)
{
ok="cun";
}
else { ok="bu"; }
}
}
catch
{
Console.WriteLine("文件错误!");
}
finally
{
con.Close();
}
return ok;
}
public static void Show()//显示该表的所有信息
{
SqlConnection con = new SqlConnection(AB);
try
{
con.Open();
SqlCommand cmd = con.CreateCommand();
cmd.CommandText = "select * from Info";
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
string sex=((bool)dr["Sex"])?"男":"女";
string date = ((DateTime)dr["Birthday"]).ToString("yyyy年MM月dd日");
Console.WriteLine(dr["Code"].ToString() + "\t" + dr["Name"].ToString() + "\t" + sex + "\t" + dr["Nation"].ToString() + "\t" + date);
}
}
catch (Exception)
{
Console.WriteLine("文件错误!");
}
finally
{
con.Close();
}
}
}
}