参考代码如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data;
using System.Data.SqlClient;
namespace DbUtil
{
public class DBHelper
{
//增删改:可以封装到一个方法;
/// <summary>
///
/// </summary>
/// <param name="sql">sql语句,insert update delte</param>
/// <param name="parameters">list:集合;动态添加数据;长度不固定</param>
/// <returns></returns>
public static bool update(String sql,List<SqlParameter>parameters) {
String url = "server=.;database=MyDb;uid=sa;pwd=123456";
//1.链接对象;
SqlConnection conn = new SqlConnection(url);
conn.Open();
//2.SqlCommand
SqlCommand cmd = conn.CreateCommand();
cmd.CommandText = sql;
if (parameters != null)
{
//继续添加参数;
for (int i = 0; i < parameters.Count; i++)
{
cmd.Parameters.Add(parameters[i]);
}
}
int result=cmd.ExecuteNonQuery();
if (result > 0)
return true;
return false;
}
public static DataTable query(String sql, List<SqlParameter> parameters)
{
String url = "server=.;database=MyDb;uid=sa;pwd=123456";
//1.链接对象;
SqlConnection conn = new SqlConnection(url);
conn.Open();
//2.SqlCommand
SqlCommand cmd = conn.CreateCommand();
cmd.CommandText = sql;
if (parameters != null)
{
//继续添加参数;
for (int i = 0; i < parameters.Count; i++)
{
cmd.Parameters.Add(parameters[i]);
}
}
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt=new DataTable();
da.Fill(dt);
return dt;
}
}
}