C#对数据库的操作(增删改查)
1、【在fig⽂件中配置】
<connectionStrings>
<add name="sqlConnection" connectionString="Data Source=服务器;Initial Catalog=数据库名称;Persist Security Info=True;User ID=⽤户名;Password=密码" pro  </connectionStrings>
2、【连接字符串】
private static readonly string StrCon = ConfigurationManager.ConnectionStrings["sqlConnection"].ToString();
3、【查询数据⽅法】
/// <summary>
/// 查询数据
/// </summary>
/// <param name="sqlStr">查询语句</param>
/// <param name="parameter">参数</param>
/// <returns></returns>
public static DataTable QueryData(string sqlStr,params SqlParameter [] parameter) {
try
{
using (SqlConnection conn = new SqlConnection())
{
conn.Open();
SqlCommand cmd = new SqlCommand(sqlStr, conn);
DataSet dt = new DataSet();基本的增删改查语句
SqlDataAdapter adapter = new SqlDataAdapter();
cmd.Parameters.AddRange(parameter);
adapter.SelectCommand = cmd;
adapter.Fill(dt);
conn.Close();
return dt.Tables[0];
}
}
catch (Exception ex)
{
throw new ApplicationException("查询数据异常"+ex.Message);
}
}
4、【更新数据⽅法】
/// <param name="parameter">参数</param>
/// <returns></returns>
public static bool UpdateData(string sqlStr, params SqlParameter[] parameter) {            try
{
using (SqlConnection conn = new SqlConnection())
{
conn.Open();
SqlCommand cmd = new SqlCommand(sqlStr,conn);
cmd.Parameters.AddRange(parameter);
var row=cmd.ExecuteNonQuery();
conn.Close();
if (row>0)
{
return true;
}
return false;
}
}
catch (Exception ex)
{
throw new ApplicationException("更新数据异常"+ex.Message) ;
}
}
5、【删除数据⽅法】
/// <summary>
/// 删除数据
/// </summary>
/// <param name="sqlStr">删除语句</param>
/// <param name="parameter">参数</param>
/// <returns></returns>
public static bool DeleteData(string sqlStr,params SqlParameter[] parameter) {            try
{
using (SqlConnection conn=new SqlConnection())
{
conn.Open();
SqlCommand cmd = new SqlCommand(sqlStr,conn);
cmd.Parameters.AddRange(parameter);
var row = cmd.ExecuteNonQuery();
conn.Close();
if (row>0)
{
return true;
}
return false;
}
}
catch (Exception ex)
{
throw new ApplicationException("删除数据异常"+ex.Message);
}
}
6、【添加数据⽅法】
/
// <param name="parameter">参数</param>
/// <returns></returns>
public static bool AddData(string sqlStr,params SqlParameter[] parameter) {
try
{
using (SqlConnection conn = new SqlConnection())
{
conn.Open();
SqlCommand cmd = new SqlCommand(sqlStr,conn);
cmd.Parameters.AddRange(parameter);
var row = cmd.ExecuteNonQuery();
conn.Close();
if (row>0)
{
return true;
}
return false;
}
}
catch (Exception ex)
{
throw new ApplicationException("添加数据异常"+ex.Message);
}
}
7、写个⽅法调⽤【查询数据⽅法】,其他三个⽅法调⽤与此类似
public DataTable GetInfo(string id) {
var sqlStr = "select * from Student where id=@id";
DataTable table = SqlHelper.QueryData(sqlStr, new System.Data.SqlClient.SqlParameter[] { new System.Data.SqlClient.SqlParameter("@id",id) });            return table;
}

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。