1. 程式人生 > >C#與SQL Server數據庫連接

C#與SQL Server數據庫連接

threading 語句 open() 成功 ssa span esc mman cat

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("關閉鏈接成功"); } } } }

C#與SQL Server數據庫連接