鏈接數據庫後的通常操做:數據庫
using System; using System.Collections.Generic; using System.Data; using System.Data.SqlClient; using System.Linq; using System.Text; using System.Threading.Tasks; namespace _03鏈接數據庫後的通常操做 { class Program { static void Main(string[] args) { //設計鏈接數據庫的字符串 //申請一個鏈接字符串變量 SqlConnectionStringBuilder tScsb = new SqlConnectionStringBuilder(); tScsb.DataSource = "127.0.0.1"; //服務器IP地址 此處爲本機(也可寫爲 localhost 或 .) tScsb.UserID = "sa";//服務器用戶名 tScsb.Password = "666";//服務器密碼 tScsb.InitialCatalog = "MyDatabase";//操做的數據庫名字 //用上述字符串申請一個數據庫鏈接對象 SqlConnection tSqlConnection = new SqlConnection(tScsb.ToString()); //若是數據庫狀態爲關閉,則打開 if (tSqlConnection.State == ConnectionState.Closed) { tSqlConnection.Open(); } //建立要執行的SQL語句 //插入一條數據 // string tSqlStr = "insert UserInfo(Name) values('傻萌萌二號')"; //修改一條數據 //string tSqlStr = "update UserInfo set Name ='傻萌萌三號' where Name='傻萌萌二號'"; //刪除一條數據 string tSqlStr = "delete UserInfo where Name='傻萌萌三號'"; //建立用於執行SQL語句的對象 SqlCommand tSqlCommand = new SqlCommand(tSqlStr, tSqlConnection);//參數1:待執行的SQL語句。參數2:已經打開的數據庫鏈接對象 try { //執行Sql語句,返回受影響行數 int tImpaceNum = tSqlCommand.ExecuteNonQuery(); //受影響行數爲1,成功插入--此處的受影響行數僅是知足修改或其餘條件的行數 if (tImpaceNum == 1) { Console.WriteLine("數據插入成功"); } } //跑出異常狀況 catch(Exception exception ) { throw new Exception(exception.Message); } finally { //最後關閉數據庫 tSqlConnection.Close(); } Console.ReadKey(); } } }
參數化Sql語句:cmd.Parameters.Add(new SqlParameter(列名,值));服務器