經(jīng)歷了萬般周折之后C#終于奇跡般的遠程連接上了數(shù)據(jù)了酬土。
1、實現(xiàn)C#控制臺應用程序連接遠程SQL服務器
SqlConnection myConnection;
//創(chuàng)建連接數(shù)據(jù)庫的字符串
// 注意下面的設置帮毁,server 數(shù)據(jù)庫服務器名稱;database 要連接的數(shù)據(jù)庫名稱 uid 登錄名 Pwd 登錄密碼
string connStr = "Server =219.216.73.145 ;database = ieLAB;uid = sa;pwd =123";
myConnection = new SqlConnection(connStr);? //構造myConnection對象
try
{
myConnection.Open();? //連接數(shù)據(jù)庫
}
catch (Exception e)
{
Console.WriteLine("{0} Second exception caught.", e);? //發(fā)生錯誤后,拋出出錯原因。
Console.ReadLine();
}
Console.WriteLine("連接成功吼肥!");? //顯示連接成功
myConnection.Close();? //關閉數(shù)據(jù)庫連接
Console.ReadLine();
2、用C#windows應用程序?qū)崿F(xiàn)登錄界面(掛遠程SQL)
注:輸入用戶名和密碼麻车,與數(shù)據(jù)庫所存數(shù)據(jù)進行匹配,匹配成功進入下一界面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();
}
}