目錄 C#登入界面連資料庫 一、在資料庫中先建立一個資料庫。 二、在VS中建立C#的windows窗體應用程式 三、在VS中連接配接到資料庫 四、設計登入界面 五、設定注冊界面 六、将form1的按鈕和form2進行關聯 七、設定form2界面的注冊按鈕 八、form1的登入按鈕設定 九、運作成果 參考文章:
資料庫命名為NamePwd,使用SQL語言建立兩個表,一個表命名為name,另一個表命名為pwd。在兩個表中都隻建立一個列。
create table [name]
(
Pname varchar(16)
)
create table [pwd]
(
pwd varchar(32)
)
運作成功後顯示效果為:

點選伺服器資料總管,右鍵選擇資料連接配接,點選添加連接配接。(也可以在工具
中選擇連接配接資料庫)。
輸入資料庫的名,在選擇或輸入資料庫名稱中選擇剛剛建立好的NamePwd資料庫。測試連接配接成功後,點選确定。
選擇工具箱視窗,組成界面form1。
選擇解決方案資料總管,右鍵項目--添加--Windows窗體。建立第二個窗體form2.
通過工具箱對form2進行布局。
輕按兩下form1的注冊按鈕,注冊按鈕代碼如下:
private void button2_Click(object sender, EventArgs e)
{
using (Form2 dlg = new Form2()) //caozuo是視窗類名,確定通路;後面的是構造函數
{
dlg.ShowDialog();
}
}
在運作之後,點選注冊按鈕可以彈出form2界面。
form2注冊按鈕代碼:
private void button1_Click(object sender, EventArgs e)
{
string connectionStr = "Data Source=DESKTOP-785QN2F;Initial Catalog=NamePwd;Persist Security Info=True;User ID=sa;Password=123456dyy";
//建立連接配接對象
SqlConnection myConnection = new SqlConnection(connectionStr);
//測試是否連接配接成功
string username = textBox1.Text; //擷取使用者名
string password = textBox2.Text; //擷取密碼
string myinsert = "insert into namepwd values('"+username+"','"+password+"')";
SqlCommand mycom = new SqlCommand(myinsert, myConnection); //定義對象并連接配接資料庫
myConnection.Open();//打開資料庫
mycom.ExecuteNonQuery(); //執行插入語句
myConnection.Close(); //關閉對象并釋放所占記憶體空間
// myConnection.Dispose();
MessageBox.Show("注冊成功,請前往登入界面登入!");
// Test f2 = new Test();
// this.Close();
// f2.Show();
}
注意: string connectionStr = "Data Source=*******;Initial Catalog=NamePwd;Persist Security Info=True;User ID=sa;Password=****";中的data source=資料庫名稱,password為SQL登入密碼
按鈕代碼如下:
private void button1_Click(object sender, EventArgs e)
{
string name = textBox1.Text;
string pwd = textBox2.Text;
if (name.Equals("") || pwd.Equals(""))//使用者名或密碼為空
{
MessageBox.Show("使用者名或密碼不能為空");
}
else //到資料庫中驗證
{
string str = "Data Source=DESKTOP-785QN2F;Initial Catalog=NamePwd;Persist Security Info=True;User ID=sa;Password=123456dyy";
string selectSql = "select count(*) from namepwd where Name='"+name+"' and pwd='"+pwd+"'";
SqlConnection con = new SqlConnection(str); //建立連接配接對象
SqlCommand mycom = new SqlCommand(selectSql, con); //定義對象并連接配接資料庫
SqlCommand cmd = new SqlCommand(selectSql,con);//定義對象并連接配接資料庫
cmd.CommandType = CommandType.Text;
con.Open(); //打開連接配接
Console.WriteLine("資料庫打開"); //正常列印說明沒問題,否則會抛出異常
// SqlDataReader sqlDataReader = mycom.ExecuteReader();
if (Convert.ToInt64(cmd.ExecuteScalar())>0)//滿足使用者名與密碼一緻,進入下一個界面
{
MessageBox.Show("登入成功!");
}
else
{
MessageBox.Show("登入失敗!\n"+"使用者名或密碼錯誤!");
}
con.Close(); //關閉連接配接
}
}
注意: string str = "Data Source=*******;Initial Catalog=NamePwd;Persist Security Info=True;User ID=sa;Password=****";中的data source=資料庫名稱,password為SQL登入密碼
點選運作,點選form1的注冊界面。
可以在SQL資料中查詢剛剛注冊的使用者資訊。
select *from name
select *from pwd