C#的SQL操作類實例。本站提示廣大學習愛好者:(C#的SQL操作類實例)文章只能為提供參考,不一定能成為您想要的結果。以下是C#的SQL操作類實例正文
本文實例講述了C#的SQL操作類,分享給大家供大家參考。詳細辦法如下:
using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using System.Windows.Forms;
namespace yjgl
{
/// <summary>
/// 數據訪問根底類(SQL)
/// </summary>
class BaseOperate
{
#region 樹立數據庫銜接
/// <summary>
/// 樹立數據庫銜接.
/// </summary>
/// <returns>前往SqlConnection對象</returns>
public SqlConnection getcon()
{
string M_str_sqlcon = "Data Source=PC-200201010009 ;Database=db_yjzl;User ID=sa;PWD=123";//銜接字符串
SqlConnection mycon = new SqlConnection(M_str_sqlcon); //創立銜接對象
return mycon;
}
#endregion
#region 執行SqlCommand命令
/// <summary>
/// 執行SqlCommand
/// </summary>
/// <param name="M_str_sqlstr">SQL語句</param>
public void getcom(string M_str_sqlstr)
{
SqlConnection sqlcon = this.getcon(); //獲取銜接字符串
sqlcon.Open(); //翻開銜接
try
{
SqlCommand sqlcom = new SqlCommand(M_str_sqlstr, sqlcon); //經過SQL語句和銜接對象創立命令對象
sqlcom.ExecuteNonQuery(); //對sqlcon執行SQL語句並前往受影響的行數
sqlcom.Dispose(); //釋放sqlcom'
}
catch (SqlException e)
{
MessageBox.Show(e.ToString(), "信息提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
finally
{
sqlcon.Close();
sqlcon.Dispose();
}
}
#endregion
#region 創立DataSet對象
/// <summary>
/// 創立一個DataSet對象
/// </summary>
/// <param name="M_str_sqlstr">SQL語句</param>
/// <param name="M_str_table">表名</param>
/// <returns>前往DataSet對象</returns>
public DataSet getds(string M_str_sqlstr, string M_str_table) //查詢
{
SqlConnection sqlcon = this.getcon();
SqlDataAdapter sqlda = new SqlDataAdapter(M_str_sqlstr, sqlcon);
DataSet myds = new DataSet();
sqlda.Fill(myds, M_str_table);
return myds;
}
#endregion
#region 創立SqlDataReader對象
/// <summary>
/// 創立一個SqlDataReader對象
/// </summary>
/// <param name="M_str_sqlstr">SQL語句</param>
/// <returns>前往SqlDataReader對象</returns>
public SqlDataReader getread(string M_str_sqlstr)
{
SqlConnection sqlcon = this.getcon();
SqlCommand sqlcom = new SqlCommand(M_str_sqlstr, sqlcon);
sqlcon.Open();
SqlDataReader sqlread = sqlcom.ExecuteReader(CommandBehavior.CloseConnection);
return sqlread;
}
#endregion
}
}
希望本文所述對大家的C#順序設計有所協助。