SQLServer 在Visual Studio的2種連線方法
一、Sql Server 在Visual Studio的連線有兩種方法:
(1)本地計算機連線;
string s = “Data Source=計算機名稱;initial Catalog=資料庫名稱;integrated Security=True”;
(2)windows身份驗證方式連線;
string cc=“Data Source = 計算機名稱; Initial Catalog = 資料庫名稱; User ID = sa; Password = 你的密碼”;
二、在Visual Studio中使用:
例1:查詢資料庫中的資料並且顯示出來
string s = “Data Source=計算機名稱;Initial Catalog=資料庫名稱;Integrated Security=True”; //此處使用本地計算機連線方式
SqlConnection conn = new SqlConnection(s); //建立連線
conn.Open(); //開啟連線
SqlCommand cmd = conn.CreateCommand();
cmd.CommandText = “select * from T_User”; //使用命令
SqlDataAdapter adapter=new SqlDataAdapter(cmd);
DataTable dt=new DataTable();
adapter.Fill(dt);
conn.Dispose(); //釋放所以資源
cmd.Dispose();
conn.Close(); //關閉連線
string realname="";
string username="";
string mobile="";
string address="";
for (int i=0;i<dt.Rows.Count;i++)
{
realname=dt.Rows[i][3].ToString();
username=dt.Rows[i][1].ToString();
mobile=dt.Rows[i][4].ToString();
address=dt.Rows[i][5].ToString();
Console.WriteLine(“姓名為{0},使用者名稱為{1},手機為{2},地址為{3}”, realname, username, mobile, address);
}
Console.ReadKey();
例2:刪除表中資料
string cc=“Data Source = 計算機名稱; Initial Catalog = 資料庫名稱; User ID = sa; Password = 你的密碼”; //使用windows身份驗證
SqlConnection conn = new SqlConnection(s);
conn.Open();
SqlCommand cmd = conn.CreateCommand();
cmd.CommandText = “delete from T_User where Id=5”;
cmd.ExecuteNonQuery();
cmd.Dispose();
conn.Close();
Console.WriteLine(“刪除成功”);
Console.ReadKey();
例3:修改表中資料
string s = “Data Source=計算機名稱;initial Catalog=資料庫名稱;integrated Security=True”;
SqlConnection conn = new SqlConnection(s);
conn.Open();
SqlCommand cmd = conn.CreateCommand();
cmd.CommandText = “update T_User set [email protected] where ID=3”;
cmd.Parameters.AddWithValue("@card", “13000000000000”);
cmd.ExecuteNonQuery();
cmd.Dispose();
conn.Close();
conn.Dispose();
Console.WriteLine(“修改成功!”);
Console.ReadKey();
例4:向表中插入資料
string s = “data source=計算機名稱;initial catalog=資料庫名稱;integrated security=true”;
SqlConnection conn = new SqlConnection(s);
conn.Open();
SqlCommand cmd = conn.CreateCommand();
cmd.CommandText = “insert into T_User(UserName,Password,RealName,Mobile,Address) values(@username,@password,@realname,@mobile,@address)”;
cmd.Parameters.AddWithValue("@username", “xingxing”);
cmd.Parameters.AddWithValue("@password", “77777”);
cmd.Parameters.AddWithValue("@realname", “星星”);
cmd.Parameters.AddWithValue("@mobile", 1300000000);
cmd.Parameters.AddWithValue("@address", “河北省北京市”);
cmd.ExecuteNonQuery();
cmd.Dispose();
conn.Close();
conn.Dispose();
Console.WriteLine(“成功插入一行”);
Console.ReadKey();