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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM