C#中窗体程序连接数据库执行SQL语句查询

用到的开发软件是VS2008 和SQL server 2008

首先就这么一个简单的窗口,以下是窗体的一些简单的代码。
 

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;

namespace HFD
{
    public partial class Login : Form
    {
        public Login()
        {
            InitializeComponent();
        }
        string username = "";
        string password = "";

        
        private void btn_Exit_Click(object sender, EventArgs e)//退出按钮
        {
            Application.Exit();
        }

        private void btn_Login_Click(object sender, EventArgs e)//登录按钮
        {  username = tb_username.Text.Trim();//帐号的文本框内容
            password = tb_password.Text.Trim();//密码文本框内容

            if(username==""||password=="")
            {
                MessageBox.Show("用户名或者密码不能为空");
            }
            if (Tools.login(username, password))
            {
                MessageBox.Show("登录成功");
            }
            else
            {
                MessageBox.Show("用户名或密码错误");
            }

        }
    }
}

然后我建了一个Tools 类,主要的代码在这一部分

新手需要注意的是,如果用到SqlConnection、SqlCommand等等,需要加入引用 using System.Data.SqlClient;

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlClient;
using System.Data;

namespace HFD
{
    class Tools
    {
        public static bool login(string username ,string password)
        {
            bool aa = sqlConnection(username, password);
            Console.WriteLine(aa);
            return aa; 
        }
        public static bool sqlConnection(string username ,string password)
        {
            
            string strSQLconn = "";
            strSQLconn += "Server=localhost;"; //Server是服务器地址,如果是本地的数据库可以直接写localhost
            strSQLconn += "initial catalog=HFD;";   //数据库名称
            strSQLconn += "user id=sa;";       //登录数据库的用户名
            strSQLconn += "password=12345;";   //数据库的登录密码,这里是我自己的,你需要输入你自己的用户名和密码
            strSQLconn += "Connect Timeout=5";  // 数据超时时间

            string sqlStr = "SELECT count(1) FROM tb_Users WHERE username='" + username +"' and password='"+password+"' ";     //数据库的查询语句

            SqlConnection conn;    //声明连接

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

            SqlCommand comm = new SqlCommand(sqlStr,conn);
            //ExecuteScalar() 方法是从数据库中只取一个值,上面的SQL语句可以表示所影响的行数
            int i = Convert.ToInt32(comm.ExecuteScalar().ToString());
            if(i>=1)
            {
                conn.Close();
                return true;
            }
            conn.Close();
            return false;
        }

    }
}

整体的样子是这样的。。。。

数据库是这样的

总体上是一个很简单的小程序,各位新手可以看看。

转载请著名出处。

猜你喜欢

转载自blog.csdn.net/feiduan1211/article/details/81512996