1. 程式人生 > >C#與SQL Server資料庫連線

C#與SQL Server資料庫連線

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.SqlClient;

namespace Demp13
{
    class Program
    {
        static void Main(string[] args)
        {
            //1.建立連線字串
            string str = "server=.;database=MySchool;uid=sa;pwd=密碼
"; // string str = "Data Source=.;Initial Catalog=MySchool;User ID=sa;Password=accp"; //2.建立connection物件 SqlConnection conn = new SqlConnection(str); try { //3.開啟連結 conn.Open(); Console.WriteLine("開啟連結成功
"); //4.準備sql語句,建立command物件,並執行sql語句 Console.WriteLine("請輸入使用者名稱"); string name = Console.ReadLine(); Console.WriteLine("請輸入密碼"); string pwd = Console.ReadLine(); string sql = "select COUNT(*) from admin where loginId='
"+name+"' and loginPwd='"+pwd+"'"; SqlCommand cmd = new SqlCommand(sql,conn); //5.執行sql語句,得到返回結果 int r= Convert.ToInt32(cmd.ExecuteScalar()); if (r > 0) { Console.WriteLine("登陸成功"); } else { Console.WriteLine("登陸失敗"); } } catch (Exception ex) { Console.WriteLine(ex.Message); } finally { //4.關閉連結 conn.Close(); Console.WriteLine("關閉連結成功"); } } } }