使用C#windows應(yīng)用程序?qū)崿F(xiàn)登錄界面(連接SQL Server)

經(jīng)歷了萬般周折之后C#終于奇跡般的遠(yuǎn)程連接上了數(shù)據(jù)了。

1、實現(xiàn)C#控制臺應(yīng)用程序連接遠(yuǎn)程SQL服務(wù)器

SqlConnection myConnection;

//創(chuàng)建連接數(shù)據(jù)庫的字符串

// 注意下面的設(shè)置,server 數(shù)據(jù)庫服務(wù)器名稱;database 要連接的數(shù)據(jù)庫名稱 uid 登錄名 Pwd 登錄密碼

string connStr = "Server =219.216.73.145 ;database = ieLAB;uid = sa;pwd =123";

myConnection = new SqlConnection(connStr);? //構(gòu)造myConnection對象

try

{

myConnection.Open();? //連接數(shù)據(jù)庫

}

catch (Exception e)

{

Console.WriteLine("{0} Second exception caught.", e);? //發(fā)生錯誤后,拋出出錯原因。

Console.ReadLine();

}

Console.WriteLine("連接成功!");? //顯示連接成功

myConnection.Close();? //關(guān)閉數(shù)據(jù)庫連接

Console.ReadLine();

2、用C#windows應(yīng)用程序?qū)崿F(xiàn)登錄界面(掛遠(yuǎn)程SQL)

注:輸入用戶名和密碼,與數(shù)據(jù)庫所存數(shù)據(jù)進(jìn)行匹配,匹配成功進(jìn)入下一界面Form2,不成功提示“用戶名或密碼錯誤!”


所需控鍵:2 Lable ?2 TextBox ?1button

具體代碼:

using System.Data.SqlClient;

private void 登錄_Click(object sender, EventArgs e)

{

string str = "Server =219.216.73.145 ;database = Test;uid = sa;pwd =123";

SqlConnection conn = new SqlConnection(str);

try

{

conn.Open();

string sql = "select * from myTest where UserID='" + txt_ID.Text + "'and Password='" + txt_password.Text + "'";

SqlCommand cmd = new SqlCommand(sql, conn);

cmd.CommandType = CommandType.Text;

SqlDataReader sdr = cmd.ExecuteReader();

if (sdr.Read())

{

Form2 f2 = new Form2();

f2.Show();

}

else

{

MessageBox.Show("賬戶或密碼有誤!");

}

}

catch (Exception a)

{

Console.WriteLine("{0} Second exception caught.", a); //發(fā)生錯誤后,拋出出錯原因

Console.ReadLine();

}

}

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容