zoukankan      html  css  js  c++  java
  • c#数据库连接学习

    /*通过C#winform程序访问数据库数据

    用到的命名空间和变量类型:

    using System.Data.SqlClient;

    SqlConnection;数据库连接类

    SqlCommand;数据库操作类

    SqlDataReader:读取 */

    //登录按钮代码
    private void button1_Click(object sender, EventArgs e) 
    {
    if (textBox1.Text == "")
    MessageBox.Show("用户名不能为空!", "提示");
    else if (textBox2.Text == "")
    MessageBox.Show("密码不能为空!", "提示");
    try //try...catch...异常处理语句
    {
    string name, pass;
    bool flag = false;
    name = textBox1.Text;
    pass = textBox2.Text; //获取用户名,密码
    string str = "Data Source=SQL服务器名称;Initial Catalog=数据库名;User ID=登录名;Password=密码;";
    SqlConnection myConn = new SqlConnection(str);//创建数据库连接类的对象
    myConn.Open(); //将连接打开
    //SQL语句:从数据库的登录表中搜索登录名,密码
    string sqlstring = "select username,password from users where username='" +name + "'and password='" + pass + "'"; 
    //执行con对象的函数,返回一个SqlCommand类型的对象
    SqlCommand command = new SqlCommand(sqlstring, myConn);
    //用cmd的函数执行语句,返回SqlDataReader对象thisReader,thisReader就是返回的结果集(也就是数据库中查询到的表数据)
    SqlDataReader thisReader = command.ExecuteReader();
    //判断用户名及密码是否正确,对flag进行赋值
    while (thisReader.Read()) 
    {
    if ((thisReader.GetValue(0).ToString().Trim()) == (name.ToString().Trim()))
    {
    if (thisReader.GetValue(1).ToString().Trim() == pass.ToString().Trim())
    {
    flag = true;
    }
    }
    }
    //用完后关闭连接,以免影响其他程序访问
    myConn.Close(); 
    if (flag)
    {
    MessageBox.Show("登陆成功!");
    Form2 F = new Form2(); //显示主页面
    F.Show();
    this.Hide();
    }
    else
    {
    MessageBox.Show("请检查你的用户名和密码!");
    textBox1.Focus();
    }
    }
    catch (Exception ex2)
    {
    MessageBox.Show("连接远程SQL数据库发生错误:" + ex2.ToString(), "错误!");
    }

    转发自:http://www.cnblogs.com/q1092813103/p/5655881.html

  • 相关阅读:
    [团队项目] Scrum 项目 3.0 SCRUM 流程的步骤2: Spring 计划
    《构建之法》第6-7章读后感
    【操作系统】实验二 作业调度模拟程序
    团队项目2.0软件改进分析MathAPP
    团队项目
    结对编程2.0
    电影(网剧))项目
    实验0 了解和熟悉操作系统
    复利计算
    学习进度条
  • 原文地址:https://www.cnblogs.com/shenghuizhang/p/7830769.html
Copyright © 2011-2022 走看看