之前學習什么課程都是抱着明白的態度,總是給自己留着某天用的到再查。現在才發現這樣的學習方法是錯的!知識了解的再多不如掌握的實 。。。。。
這段時間,我們這些所謂的在校大學生和所有的學校的大學生都一樣,以前玩的越開心的孩子,此刻是最忙的孩子,尤其是計算機專業的。我們的期末考試不是做卷子,而是上交畢業作品。。。我這個不算差的學生就很忙了,不過我還有時間給那些到現在還沒有按軟件或者配置環境的同學搭建開方環境,雖然這活我干煩了,但是同學一場,求到你了,你還能說什么??浪費了我多少時間??
好了,言歸正傳。。。。
先說說數據的連接吧。。起初我是用的:在每一個winform的窗口中都添加 引用:using System.Data.SqlClient;
string strConnect = "Data Source=CAI-PC\\SQLEXPRESS;Initial Catalog=MyData1;Persist Security Info=True;User ID=sa;Password=******";
這種連接方式不算是上策之方法 ,因為數據如果改變就要改每一個winform窗口,對於開發和后期應用的帶來了很多不方便。。
我現在采用的是:新建一個獨立的類,用來連接數據庫。在新類頭部分添加引用空間:suing System.Data.SqlClient;
我的代碼如下:
namespace 學生信息管理系統
{
public class Datalink
{
public static String GetConnString()
{
SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder();//實例化
builder.DataSource = ".";//本機數據庫服務器
builder.InitialCatalog = "信息管理";//數據庫名
builder.IntegratedSecurity = false;//登陸方式:fales為身份登陸,true為系統登陸
builder.UserID = "aab";//數據庫用戶
builder.Password = "123";//數據庫用戶密碼
string connStr = builder.ToString();
return connStr;
}
}
}
然后在每個winform窗口添加語句:
string strConnect = Datalink.GetConnString();
SqlConnection ole = new SqlConnection(strConnect);
實現數據庫連接。。。。
登陸就是sql查詢數據,就是簡單的數據對比,如下代碼:
SqlCommand com = new SqlCommand("select 密碼 from 用戶 where 用戶='" + txtnames.Text.Trim() + "'", ole);
string pwd = com.ExecuteScalar() as String;//ExecuteScalar方法從數據庫中檢索單個值,回傳的必為 Object 類型,因此必須由程序員,手動將其強制轉型為
//.NET 的 int 或 string 等想要的類型,以便直接指派給 int 或 string 類型的變量,或顯示在頁面上的控件中
ole.Close();
if (pwd == null)
{
MessageBox.Show("請輸入正確的用戶名");
txtnames.Text = txtpaws.Text = null;
}
else
{
pwd = pwd.Trim();
if (pwd == txtpaws.Text)
{
main frm = new main();
frm.Show();
this.Hide();
}
else
{
MessageBox.Show("請輸入正確的密碼");
txtpaws.Text = null;
}
登陸功能是寫入數據庫:
private void ok_Click(object sender, EventArgs e) { string username = txtname.Text.Trim(); string password1 = txtpaw.Text.Trim(); string password2 = txtpaw1.Text.Trim(); string mail = email.Text.Trim(); if (password1 == password2) { string strConnect = Datalink.GetConnString(); SqlConnection conn = new SqlConnection(strConnect); conn.Open(); SqlCommand comm = new SqlCommand("insert into 用戶(用戶,密碼,E-mail) values('" + username + "','" + password1 + "','"+email+"')", conn); if (comm.ExecuteNonQuery() > 0) { MessageBox.Show("請登錄"); } conn.Close();
} else { MessageBox.Show("確認密碼有誤"); txtpaw1.Text = null; } }