• winform基础——数据访问及几个案例


    数据访问分为三个部分:(1)创建链接(2)创建与执行命令(3)读取或准备相关数据

    一,需要引用的命名空间

    using data;

    using data.SqlClient;

    二,创建与数据库的链接——SqlConnection(链接类)

    1,链接字符串:server=目标服务器的IP地址;database=数据库名;uid=数据库的登录名;pwd=数据库的登录密码

    server=.; database=mydb; uid=sa; pwd=123

    2,实例化——构造

    SqlConnection conn=new SqlConnection(链接字符串);

    3,属性

    state:用来描述链接当前的状态  closed:链接处于关闭状态   open:链接处于打开状态

    4,方法

    open():打开链接

    close():关闭链接

    5,案例

    (1)定义链接字符串。
    string connectionString = "server=.;database=mydb;uid=sa;pwd=123";
    (2)构造链接对象
    SqlConnection conn = new SqlConnection(connectionString);

    SqlConnection conn = new SqlConnection();
    conn.ConnectionString = connectionString;
    (3)打开链接
    conn.Open();
    (4)关闭链接
    conn.Close();

    三,向数据传递sql语句或存储过程并执行——sqlcommand(命令类)

    1,构造

    SqlCommand cmd=conn.CreateCommand();

    SqlCommand cmd=new SqlCommand();

    2,属性

    connection:(SqlConnection类型)指定通过哪个链接对象来操作数据库

    CommandText:(string类型)要执行的sql语句或存储过程名

    3,方法

    ExecuteNonQuery():执行非查询命令,返回影响的行数。一般用来执行增删改的语句

    ExecuteReader():执行读取命令,返回一个读取器对象。一般用来执行查询语句

    4,案例

    string connectionString = "server=.;database=mydb;uid=sa;pwd=123";
    SqlConnection conn = new SqlConnection(connectionString);
    conn.Open();

    //操作数据库
    SqlCommand cmd = new SqlCommand();
    cmd.Connection = conn;
    cmd.CommandText = "insert into student values('s001','张三','1','清华大学','1990-6-1')";
    cmd.ExecuteNonQuery();

    conn.Close();

    四,从查询的结果集中把数据逐个读取出来——SqlDataReader(读取器类)

    1,构造

    只有唯一的一种构造方式

    SqlDataReader dr=cmd.ExecuteReader();

    说明:只读,只向前,读取器工具,每次只读取一条记录,内存中只占一条记录的空间

    2,属性

    HasRows:返回值为bool类型,判断是否有数据可读,是否查出数据来了

    3,方法

    Read():返回值为bool类型,把结果集中当前行的内容读取到内存中的DataReader中来,读出来了返回true,没有数据可读返回false

    在使用SqlDataReader读取某列数据时,必须先使用Read()方法把数据先取到内存中的SqlDataReader中。

    从SqlDataReader中读取某列值的时候,使用方法:
    (1)dr[列的下标/列的索引号]
    (2)dr["列名"]
    (3)dr.GetInt(索引号) dr.GetString(索引号) ...

    4,案例

    (1)登录的例子(输入用户名和密码验证是否正确)

    Console.Write("用户名:");
    string uid = Console.ReadLine();
    Console.Write("密码:");
    string pwd = Console.ReadLine();

    //操作数据库
    SqlConnection conn = new SqlConnection("server=.;database=mydb;uid=sa;pwd=123");
    conn.Open();

    SqlCommand cmd = conn.CreateCommand();
    cmd.CommandText = "select * from Login where UserName='"+uid+"' and password='"+pwd+"' "; //查询
    SqlDataReader dr = cmd.ExecuteReader(); //生成读取器对象。
    if (dr.HasRows)
    {
    Console.WriteLine("OK");
    }
    else
    {
    Console.WriteLine("Error");
    }

    conn.Close();

     (2)多表查询(将两个表中的数据联合显示出来):尽量不要用join连接查询,写多个函数,在主函数内调用即可

    namespace ConsoleApplication1
    {
    class Program
    {
    public const string CONNECTIONSTRING = "server=.;database=mydb;uid=sa;pwd=123";   //在函数外定义链接字符串常量
    static string GetNationName(string code)     
    {
    string str = "";

    //根据民族代号查询民族名称
    SqlConnection conn = new SqlConnection(CONNECTIONSTRING);
    conn.Open();

    SqlCommand cmd = conn.CreateCommand();
    cmd.CommandText = "select * from nation where code='" + code + "' ";
    SqlDataReader dr = cmd.ExecuteReader();
    if (dr.HasRows)
    {
    dr.Read();
    str = dr["Name"].ToString();
    }
    else
    {
    str = "未知";
    }

    conn.Close();

    return str;
    }
    static string GetWorks(string code)  //通过代号查询工作经历
    {
    string str = "";

    SqlConnection conn = new SqlConnection(CONNECTIONSTRING);
    conn.Open();

    SqlCommand cmd = conn.CreateCommand();
    cmd.CommandText = "select * from work where infocode='" + code + "'";
    SqlDataReader dr = cmd.ExecuteReader();
    while (dr.Read())
    {
    str += ((DateTime)dr["StartDate"]).ToString("yyyy年MM月dd日") + " ";
    str += ((DateTime)dr["EndDate"]).ToString("yyyy年MM月dd日") + " ";
    str += dr["Firm"].ToString()+ " ";
    str += dr["Depart"].ToString() + " ";
    }

    conn.Close();

    return str;
    }
    static void Main(string[] args)
    {
    //显示
    SqlConnection conn = new SqlConnection(CONNECTIONSTRING);
    conn.Open();

    SqlCommand cmd = conn.CreateCommand();

    cmd.CommandText = "select * from info";
    SqlDataReader dr = cmd.ExecuteReader();
    while (dr.Read())
    {
    string code = dr["code"].ToString();
    string name = dr["name"].ToString();
    string sex = ((bool)dr["Sex"]) ? "男" : "女";
    string nation = GetNationName(dr["nation"].ToString());
    string birthday = ((DateTime)dr["birthday"]).ToString("yyyy年MM月dd日");

    Console.ForegroundColor = ConsoleColor.Yellow;
    Console.WriteLine(code + " " + name + " " + sex + " " + nation + " " + birthday);
    Console.ResetColor();
    //显示工作简历
    Console.WriteLine("****工作简历****");
    Console.WriteLine(GetWorks(code));
    }

    conn.Close();
    }
    }
    }

    (3)向info表中插入数据(要注意先检查输入信息的格式是否正确和主外键是否冲突)

    namespace ConsoleApplication1
    {
    class Class1
    {
    public const string CONNECTIONSTRING = "server=.;database=mydb;uid=sa;pwd=123";
    public static bool Check(string columnName, string value)  //检查输入的性别和生日格式是否正确
    {
    if (columnName == "sex")
    {
    if (value == "0" || value == "1")
    {
    return true;
    }
    else
    {
    Console.WriteLine("性别格式不正确");
    return false;
    }
    }
    else if (columnName == "birthday")
    {
    try
    {
    Convert.ToDateTime(value);
    return true;
    }
    catch
    {
    Console.WriteLine("生日格式不正确");
    return false;
    }
    }
    else
    {
    return true;
    }
    }
    public static bool CheckPK(string pk)  //检查主键code是否与输入冲突
    {
    bool notHasPK = true;
    SqlConnection conn = new SqlConnection(CONNECTIONSTRING);
    conn.Open();

    SqlCommand cmd = conn.CreateCommand();
    cmd.CommandText = "select * from info where code='" + pk + "'";
    SqlDataReader dr = cmd.ExecuteReader();
    if (dr.HasRows)
    {
    notHasPK = false;
    Console.WriteLine("主键已存在");
    }
    else
    {
    notHasPK = true;
    }
    conn.Close();

    return notHasPK;
    }
    public static bool HasNation(string nationCode)  //检查外键
    {
    bool hasNation = true;
    SqlConnection conn = new SqlConnection(CONNECTIONSTRING);
    conn.Open();

    SqlCommand cmd = conn.CreateCommand();
    cmd.CommandText = "select * from nation where code='" + nationCode + "'";
    SqlDataReader dr = cmd.ExecuteReader();
    if (dr.HasRows)
    {
    hasNation = true;
    }
    else
    {
    hasNation = false;
    Console.WriteLine("民族代号输入不正确");
    }
    conn.Close();
    return hasNation;
    }
    public static void AddInfo(string code, string name, string sex, string nation, string birthday)   //插入信息函数
    {
    SqlConnection conn = new SqlConnection(CONNECTIONSTRING);
    conn.Open();

    SqlCommand cmd = conn.CreateCommand();
    cmd.CommandText = "insert into info values('" + code + "','" + name + "','" + sex + "','" + nation + "','" + birthday + "')";
    cmd.ExecuteNonQuery();

    conn.Close();
    }
    public static void Main111(string[] args)
    {
    //输入
    Console.Write("代号:");
    string code = Console.ReadLine();
    Console.Write("姓名:");
    string name = Console.ReadLine();
    Console.Write("性别(0,1):");
    string sex = Console.ReadLine();
    Console.Write("民族:");
    string nation = Console.ReadLine();
    Console.Write("生日:");
    string birthday = Console.ReadLine();
    //检查
    bool isOK = CheckInput(code, sex, nation, birthday);

    //插入
    if (isOK == true)
    {
    AddInfo(code, name, sex, nation, birthday);
    }
    }

    private static bool CheckInput(string code, string sex, string nation, string birthday)   //验证所有检查是否都执行完
    {
    //1.对输入的数据格式进行检查
    bool isOK = true;
    bool isOK1 = Check("sex", sex);
    bool isOK2 = Check("birthday", birthday);

    //2.对主外键进行检查
    bool isOK3 =CheckPK(code);
    bool isOK4 = HasNation(nation);

    isOK = isOK && isOK1 && isOK2 && isOK3 && isOK4;
    return isOK;
    }
    }
    }

    (4)从info表中删除数据(注意有外键的情况,有两种方法删除:一,在数据库中使用级联删除。二,写代码先删除从表再删除主表)

    namespace ConsoleApplication1
    {
    class Class2
    {
    public const string CONNECTIONSTRING = "server=.;database=mydb;uid=sa;pwd=123";
    static string GetNationName(string code)
    {
    string str = "";

    //根据民族代号查询民族名称
    SqlConnection conn = new SqlConnection(CONNECTIONSTRING);
    conn.Open();

    SqlCommand cmd = conn.CreateCommand();
    cmd.CommandText = "select * from nation where code='" + code + "' ";
    SqlDataReader dr = cmd.ExecuteReader();
    if (dr.HasRows)
    {
    dr.Read();
    str = dr["Name"].ToString();
    }
    else
    {
    str = "未知";
    }

    conn.Close();

    return str;
    }
    //显示所有人员信息
    public static void Show()
    {
    //显示
    SqlConnection conn = new SqlConnection(CONNECTIONSTRING);
    conn.Open();

    SqlCommand cmd = conn.CreateCommand();
    cmd.CommandText = "select * from info";
    SqlDataReader dr = cmd.ExecuteReader();
    while (dr.Read())
    {
    string code = dr["code"].ToString();
    string name = dr["name"].ToString();
    string sex = ((bool)dr["Sex"]) ? "男" : "女";
    string nation = GetNationName(dr["nation"].ToString());
    string birthday = ((DateTime)dr["birthday"]).ToString("yyyy年MM月dd日");

    Console.WriteLine(code + " " + name + " " + sex + " " + nation + " " + birthday);
    }

    conn.Close();
    }
    //检查主键是否存在
    public static bool CheckPK(string pk)
    {
    bool hasPK = true;
    SqlConnection conn = new SqlConnection(CONNECTIONSTRING);
    conn.Open();

    SqlCommand cmd = conn.CreateCommand();
    cmd.CommandText = "select * from info where code='" + pk + "'";
    SqlDataReader dr = cmd.ExecuteReader();
    hasPK = dr.HasRows;
    conn.Close();

    return hasPK;
    }
    public static void DeleteInfo(string pk)
    {
    SqlConnection conn = new SqlConnection(CONNECTIONSTRING);
    conn.Open();

    SqlCommand cmd = conn.CreateCommand();
    cmd.CommandText = "delete from family where InfoCode='" + pk + "'";
    cmd.ExecuteNonQuery();
    cmd.CommandText = "delete from work where InfoCode='" + pk + "'";
    cmd.ExecuteNonQuery();
    cmd.CommandText = "delete from info where code='" + pk + "'";
    cmd.ExecuteNonQuery();

    conn.Close();
    }
    public static void Main(string[] args)
    {
    //显示
    Show();
    //输入要删除的人员代号
    Console.Write("输入要删除的人员:");
    string code = Console.ReadLine();
    //删除
    //看看有没有这个代号的人员,如果没有就提示代号输入错误。
    bool pkIsOK = CheckPK(code);
    if (pkIsOK == true)
    {
    //执行删除
    DeleteInfo(code);
    Console.WriteLine("删除成功");
    }
    else
    {
    Console.WriteLine("找不到要删除的人员代号,删除失败。请重新检查要删除的人员代号。");
    }

    //显示
    Show();
    }
    }
    }

  • 相关阅读:
    Python爬虫开源项目代码,爬取微信、淘宝、豆瓣、知乎、新浪微博、QQ、去哪网等 代码整理
    python ---split()函数讲解
    常见的操作系统及linux发展史
    第五次作业
    第四次软件工程作业
    软件工程——第三次作业
    软件工程--第二次作业
    软件工程--第一次作业
    在SQL Server中调用.NET程序集
    c#中使用ABCpdf处理PDF,so easy
  • 原文地址:https://www.cnblogs.com/William-1234/p/4479619.html
Copyright © 2020-2023  润新知