zoukankan      html  css  js  c++  java
  • 使用ADO.NET访问数据库

    Program

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using System.Data.SqlClient;
    namespace 打开数据库
    {
    class Program
    {
    static void Main(string[] args)
    {
    #region 连接数据库
    //步骤一:配置参数(连接到服务器,连接的数据库名称,用户名,密码)
    string str = "Data Source=.;Initial Catalog=Myschool;User ID=sa;pwd=1";
    //步骤二:创建Connection对象连接数据库(SqlConnection)
    SqlConnection con = new SqlConnection(str);
    //步骤三:打开数据库
    con.Open();
    Console.WriteLine("打开数据库成功!");

    //步骤N:将数据库关闭
    con.Close();
    Console.WriteLine("关闭数据库成功!");
    #endregion

    #region 数据库异常
    try
    {
    con.Open();

    }
    catch(SqlException ex){
    Console.WriteLine("出现异常"+ex); 
    }
    catch (Exception ex)
    {
    Console.WriteLine("出现异常!" + ex);
    }
    finally {
    con.Close();
    Console.WriteLine("关闭数据库成功!");
    }
    #endregion

    #region 登录
    Console.WriteLine("请输入用户名:");
    string loginID = Console.ReadLine();
    Console.WriteLine("请输入密码:");
    string loginPwd = Console.ReadLine();
    User user = new User();
    user.login(loginID, loginPwd);
    #endregion
    Console.ReadLine();
    }
    }
    }

    ConnectionDB类

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using System.Data.SqlClient;
    namespace 打开数据库
    {
    class ConnectionDB
    {
    static string str = "Data Source=.;Initial Catalog=Myschool;User ID=sa;password=1";
    public SqlConnection con = new SqlConnection(str);
    public void OpenDB() 
    {
    try
    {
    con.Open();
    }
    catch (Exception ex)
    {

    Console.WriteLine("发生异常!"+ex);
    }
    }
    public void CloseDB() 
    {
    con.Close();
    }
    }
    }

    User类

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using System.Data.SqlClient;
    namespace 打开数据库
    {
    class User
    {
    ConnectionDB bd = new ConnectionDB();
    public void login(string StudentNo, string loingPwd)
    {
    string sql = "SELECT COUNT(1) FROM Student WHERE StudentNo='" + StudentNo + "' AND Loginpwd='" + loingPwd + "'";
    Console.WriteLine(sql);
    bd.OpenDB();
    SqlCommand cmd = new SqlCommand(sql, bd.con);
    int count = (int)cmd.ExecuteScalar();
    if (count > 0)
    {
    Console.WriteLine("登录成功!");
    }
    else
    {
    Console.WriteLine("登录失败!");
    }

    }


    }
    }

  • 相关阅读:
    在IE浏览器中url传参长度问题
    Linq语句的认识
    关于选择表达式以及判断语句的书写,可以让代码更加的清晰。
    C#/对线程的认识
    Js/如何修改easyui修饰的input的val值
    Java Lambda表达式中的this
    MySQL USING关键词/USING()函数的使用
    复杂SQL查询
    Java 修饰符
    Git:idea中将当前分支修改的内容提交到其他分支上
  • 原文地址:https://www.cnblogs.com/wnwn/p/10169362.html
Copyright © 2011-2022 走看看