C#數據庫連接方式(類的形式)
更新時間:2023年07月12日 10:25:34 作者:不想學習只想玩
這篇文章主要介紹了C#數據庫連接方式(類的形式),具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
C#數據庫連接(類的形式)
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Data.SqlClient; namespace systemprotect { class DataCon { static string strCon = "server=.;database =自己的數據庫名;uid=sa;pwd=自己的數據庫密碼";//數據庫連接串 SqlConnection conn = new SqlConnection(strCon); public SqlDataReader query(string str)//查詢 { if (this.conn.State == System.Data.ConnectionState.Closed)//判斷連接是否打開 { this.conn.Open(); } SqlCommand cmd = new SqlCommand(str, conn); return cmd.ExecuteReader(); } public int insert(string str)//插入,刪除,更新 返回影響的行數 { if (this.conn.State == System.Data.ConnectionState.Closed) { this.conn.Open(); } SqlCommand cmd = new SqlCommand(str, conn); return cmd.ExecuteNonQuery(); } public void close()//關閉連接 { conn.Close(); } } }
C#連接數據庫的步驟和相關的方法調用
//第一步:創(chuàng)建Connection 數據庫連接對象 SqlConnection conn = new SqlConnection("server = . ; uid = sa ; pwd = jnos;database = JINGDONGDB"); //第二步:打開連接數據庫 conn.Open(); //第三步:使用數據庫 string sql = $@"select ProductNo, ProductName, ProductImage, Price,password from Product where ProductNo={_ProductNo}and password='{_password}'";//@符號表示可以換行,代碼也連接在一起 SqlCommand command = new SqlCommand(sql,conn); SqlDataReader reader = command.ExecuteReader();// if (reader.Read()) { string ProductNo = reader["ProductNo"].ToString(); string ProductName = reader["ProductName"].ToString(); MessageBox.Show($"歡迎{ProductName}登錄成功"); }//在數據庫里面是為 next() 有數據為 true 沒有數據為 flase else { MessageBox.Show("賬號或密碼錯誤,請重新輸入!"); } //int resule = command.ExecuteNonQuery();//添加、刪除、修改(返回行數受影響)接SqlCommand command = new SqlCommand(sql,conn); //行 是添加刪除修改的步驟 //object result = command.ExecuteScalar();//查詢聚合函數用到 //if(resule > 0) //{ // MessageBox.Show("刪除成功"); //} //else //{ // MessageBox.Show("刪除失敗"); //} //第四步:關閉連接對象 conn.Close();
相關的方法調用
command.ExecuteNonQuery
:添加、刪除、修改(返回行數受影響command.ExecuteScalar
:查詢聚合函數command.ExecuteReader
:查詢單列函數
總結
以上為個人經驗,希望能給大家一個參考,也希望大家多多支持腳本之家。