zoukankan      html  css  js  c++  java
  • 怎样实现winform与数据库连接

    首先创建一个类,写一个专门用来查询有没有这个用户名密码的方法,

    然后在按钮的事件中实例化并调用这个方法.

    1.查询有没有这个类的方法

    复制代码
    using System;
    using System.Collections.Generic;
    using System.Data.SqlClient;
    using System.Linq;
    using System.Text;
    
    namespace WindowsFormsApplication2.App_Code
    {
        public class UserData
        {
            SqlConnection conn = null;
            SqlCommand cmd = null;
            public UserData()
            {
                conn = new SqlConnection("server=.;database=ODA;user=sa;pwd=123;");
                cmd = conn.CreateCommand();
            }
            public bool have(string a, string b)
            {
                bool c = false;
                cmd.CommandText = "select *from Users where Username=@a and Password=@b ";
                cmd.Parameters.Clear();
                cmd.Parameters.AddWithValue("@a", a);
                cmd.Parameters.AddWithValue("@b", b);
                conn.Open();
                SqlDataReader dr = cmd.ExecuteReader();
                if (dr.HasRows)
                {
                    c = true;
                }
                conn.Close();
                return c;
            }
        }
    }
    复制代码

    2.对按钮添加点击事件

    复制代码
    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Linq;
    using System.Text;
    using System.Windows.Forms;
    using WindowsFormsApplication2.App_Code;
    
    namespace WindowsFormsApplication2
    {
        public partial class Form1 : Form
        {
            public Form1()
            {
                InitializeComponent();
            }
    
            private void button1_Click(object sender, EventArgs e)
            {
                if (new UserData().have(textBox1.Text, textBox2.Text))
                {
                    MessageBox.Show("存在该用户");
                }
                else
                {
                    MessageBox.Show("不存在该用户"); 
                }
            }
        }
    }
    复制代码
  • 相关阅读:
    非重复随机序列生成算法
    IE浏览器整页截屏程序
    地铁线路图的设计与实现
    拓扑排序算法的一个应用
    洛谷 P4450 双亲数
    洛谷 P2183 [国家集训队]礼物
    洛谷 P4159 [SCOI2009]迷路
    CF86D Powerful array
    Catalan数
    SP3266 KQUERY Kquery
  • 原文地址:https://www.cnblogs.com/weiyu11/p/6793073.html
Copyright © 2011-2022 走看看