---------------------
作者:Cambridge 來源:CSDN 原文:https://blog.csdn.net/cambridgeacm/article/details/7970836
VS連接SQL Server 2008,並實現登錄和注冊功能
建一個Student數據庫,其中含有兩張表,一個是用戶表,其中包含能夠登錄該數據庫的用戶名和密碼,還有一個是信息表,含有學生的信息
在VS中建一個Windows窗體應用程序,實現用戶的登錄和注冊功能,登錄時檢索用戶名和密碼與用戶表中的內容是否匹配,若匹配成功提示成功登錄,否則登錄失敗,注冊時檢索用戶名和密碼和用戶表中的內容是否有相同,若果有相同的提示該用戶名已被注冊,否則注冊成功
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Data.SqlClient;
using System.Windows.Forms;
using System.Data.OleDb;
namespace 登錄數據庫
{
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
if (textBox1.Text == "" || textBox2.Text == "")
MessageBox.Show("提示:請輸入用戶名和密碼!", "警告");
SqlConnection conn = new SqlConnection("Data Source=(local);Initial Catalog=Student;Integrated Security=True");
conn.Open();
SqlCommand cmd = new SqlCommand("select * from 用戶 where 用戶名='" + textBox1.Text.Trim() + "' and 密碼='" + textBox2.Text.Trim() + "'", conn);
SqlDataReader sdr = cmd.ExecuteReader();
sdr.Read();
if (sdr.HasRows)
MessageBox.Show("登錄成功!", "提示");
else
MessageBox.Show("提示:學生用戶名或密碼錯誤!","警告");
conn.Close();
}
private void button2_Click(object sender, EventArgs e)
{
if (textBox1.Text == "" || textBox2.Text == "")
MessageBox.Show("請輸入用戶名、密碼!", "警告");
else
{
SqlConnection conn = new SqlConnection("Data Source=(local);Initial Catalog=Student;Integrated Security=True");
conn.Open();
SqlCommand cmd = new SqlCommand("select * from 用戶 where 用戶名='" + textBox1.Text.Trim()+"'", conn);
SqlDataReader sdr = cmd.ExecuteReader();
sdr.Read();
if (sdr.HasRows)
MessageBox.Show("該用戶已注冊,請使用其他用戶名", "提示");
else
{
sdr.Close();
string myinsert = "insert into 用戶(用戶名,密碼) values ('" + textBox1.Text + "','" + textBox2.Text + "')";
SqlCommand mycom = new SqlCommand(myinsert, conn); //定義OleDbCommnad對象並連接數據庫
mycom.ExecuteNonQuery(); //執行插入語句
conn.Close(); //關閉對象並釋放所占內存空間
conn.Dispose();
MessageBox.Show("您已注冊成功!");
}
}
}
}
}
---------------------
登錄界面
注冊界面