在c#中怎么把操作数据库的增删改查写成一个类要用的时候直接写SQL语句就行了
展开全部
using System;
using System.Data;
using System.Data.SqlClient;
namespace MyUtils
{
public class MySQLUtil
{
public static readonly string ConnectionString = @"Data Source=*** Catalog=***;Persist Security Info=True;User ID=sa;Password=********";
public static SqlConnection getConnection()
{
return new SqlConnection(ConnectionString);
}
public static int ExecuteNonQuery(String sqlText)
{
SqlCommand cmd = new SqlCommand();
using (SqlConnection conn = new SqlConnection(ConnectionString))
{
conn.Open();
cmd.Connection = conn;
cmd.CommandText = sqlText;
int value = cmd.ExecuteNonQuery();
return value;
}
}
public static SqlDataReader ExecuteReader(String sqlText, SqlConnection conn)
{
SqlCommand cmd = new SqlCommand();
try
{
conn.Open();
cmd.Connection = conn;
cmd.CommandText = sqlText;
SqlDataReader reader = cmd.ExecuteReader();
return reader;
}
catch (Exception e)
{
conn.Close();
throw e;
// return null;
}
}
public static DataSet ExecuteDataSet(String sqlText)
{
SqlCommand cmd = new SqlCommand();
DataSet ds = new DataSet();
using (SqlConnection conn = new SqlConnection(ConnectionString))
{
conn.Open();
cmd.Connection = conn;
cmd.CommandText = sqlText;
using (SqlDataAdapter da = new SqlDataAdapter())
{
da.SelectCommand = cmd;
da.Fill(ds);
return ds;
}
}
}
public static DataTable ExecuteDataTable(String sqlText)
{
SqlCommand cmd = new SqlCommand();
DataTable dt = new DataTable();
using (SqlConnection conn = new SqlConnection(ConnectionString))
{
conn.Open();
cmd.Connection = conn;
cmd.CommandText = sqlText;
using (SqlDataAdapter da = new SqlDataAdapter())
{
da.SelectCommand = cmd;
da.Fill(dt);
return dt;
}
}
}
public static int getSingleInt(String sqlText)
{
SqlCommand cmd = new SqlCommand();
SqlConnection conn = new SqlConnection(ConnectionString);
try
{
conn.Open();
cmd.Connection = conn;
cmd.CommandText = sqlText;
SqlDataReader reader = cmd.ExecuteReader();
reader.Read();
if (reader.IsDBNull(0))
return 0;
else
return reader.GetInt32(0);
}
catch (Exception e)
{
conn.Close();
return -1;
}
finally { conn.Close(); }
}
}
}
追问
谢谢 请问public static SqlDataReader ExecuteReader(String sqlText, SqlConnection conn)这个方法应该怎么用阿 不知道这个怎么用
光点科技
2023-08-15 广告
2023-08-15 广告
通常情况下,我们会按照结构模型把系统产生的数据分为三种类型:结构化数据、半结构化数据和非结构化数据。结构化数据,即行数据,是存储在数据库里,可以用二维表结构来逻辑表达实现的数据。最常见的就是数字数据和文本数据,它们可以某种标准格式存在于文件...
点击进入详情页
本回答由光点科技提供
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询