您的位置:首页 > 数据库

连接数据库执行增删改查(返回行数、主键值)所有方法

2015-12-23 10:26 405 查看
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;

namespace BimWeb.DataConnection
{
public class MSSqlHelper
{
public MSSqlHelper()
{
//UserData 在Web.config中的配置
// <configuration>
//  <connectionStrings>
//  <add name="UserData" connectionString="data source=.;initial catalog=sxazERP;user id=sa;password=sa;multipleactiveresultsets=True;application name=EntityFramework" providerName="System.Data.SqlClient" />
//  </connectionStrings>
//  </configuration>
__ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings["UserData"].ConnectionString;
}
private string __ConnectionString;

#region 此方法执行sql语句,返回影响的行数,用于新增,修改,删除
/// <summary>
/// 此方法执行sql语句,返回影响的行数,用于新增,修改,删除
/// </summary>
/// <param name="SqlCommand">SQL语句</param>
/// <returns>影响的行数</returns>
public int ExecuteNonQuery(string SqlCommand) //,  System.Data.SqlClient.SqlParameter[] Parameters
{
//sql语句例如:    SqlCommand = "delete from BimWeb_ModelInfo where ModelIndexId=1";
SqlConnection conn = new SqlConnection(__ConnectionString);
conn.Open();
SqlCommand cmd = new SqlCommand(SqlCommand, conn);
int backValue = cmd.ExecuteNonQuery();
conn.Close();
return backValue;
}
#endregion

#region 此方法执行sql语句,返回新增的主键
public int ExecuteScalerB(string SqlCommand) //, System.Data.SqlClient.SqlParameter[] Parameters
{
//sql语句例如: string InsertBimWeb_Model = "insert into BimWeb_Model(UniqueId,Name,RFCModelFilePath,ModelTypeIndexId,D3ModelImagePath,ModelSetIndexId) values('" + uniquid + "','" + name + "','" + RfaFile + "'," + categoryid + ",'" + ImageFile + "'," + setID + ");select @@IDENTITY";

int backValue = -1;
SqlConnection conn = new SqlConnection(__ConnectionString);
conn.Open();
SqlCommand cmd = new SqlCommand(SqlCommand, conn);
backValue = Convert.ToInt16(cmd.ExecuteScalar().ToString());
conn.Close();
return backValue;
}
#endregion

#region 执行查询语句,返回datatable
public DataTable ExecuteDataTable(string SqlCommand, string TableName = "temp")
{
//语句及调用实例:
// string sqlC = "select Id,Name,ParentIndexId from BimWeb_ModelType ";
// DataTable dtModelType = MHelper.ExecuteDataTable(sqlC, "BimWeb_ModelType");

DataTable __temp = null;
using (SqlConnection conn = new SqlConnection(__ConnectionString))
using (SqlCommand cmd = new SqlCommand(SqlCommand, conn))
using (SqlDataAdapter ada = new SqlDataAdapter(cmd))
using (System.Data.DataSet ds = new System.Data.DataSet())
{
ada.Fill(ds, TableName);
__temp = ds.Tables[TableName];
}
return __temp;
}
#endregion
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  数据库 class