在C#下使用sql語句(查詢,插入,更新,刪除……)


需要說明的是,我使用的是sql server 2000為服務器。

按照以下的幾步,就可以很順利的連接到服務器,執行基本的sql操作了。

第一步 連接服務器
SqlConnection thisConnection = new SqlConnection(@"Server = (local); Integrated Security = True;" + "Database = hospital");
thisConnection.Open();

第二步 新建命令

SqlCommand thiscommand = thisConnection.CreateCommand();

第三步 給問題文本賦值

thiscommand.CommandText = "insert into Users(Telephone) values('02787546321')"

這里的字符串就是需要執行的sql命令

第四步 執行命令

分為三種命令,相應調用不同的方法:

1 不需要查詢的(插入,更新,刪除)

thiscommand.ExecuteNonQuery();

該函數會返回收到影響的總行數。

2 只需要查詢一個值的

thiscommand.ExecuteScalar();

該函數會返回使用的sql語言查詢的結果

3 需要同時查詢得到多個值的

SqlDataReader QuesReader = thiscommand.ExecuteReader();  //新建一個SqlDataReader 
QuesReader.Read();        //讀取一行數據到Reader中
thisQues[0] = (string)QuesReader["Text"];  //將Reader中的數據讀取走
QuesReader.Close();   //關閉Reader

第五步 關閉連接

thisConnection.Close();


免責聲明!

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



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