最近需要用到连接数据库的DBHelper.cs类,网上找了一大圈,没找到比较简洁的简化版,就自己手写了一个。Asp.net和winform窗体都可以用,具体代码如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlClient;
using System.Data;
namespace Exe
{
class DBHelper
{
//数据库连接字符串
//private static string conStr = "server=TUAN-20170226JH;database=Iphone;uid=sa;pwd=scce;";
private static string conStr = "Data Source = 刘梦凡; Initial Catalog = Iphone; Integrated Security = True;";
/// <summary>
/// 增删改,返回受影响的行数
/// </summary>
/// <param name="sql">查询sql</param>
/// <returns></returns>
public static int ExecuteNonQuery(string sql)
{
SqlConnection con = new SqlConnection(conStr);
con.Open();
SqlCommand cmd = new SqlCommand(sql,con);
int rows = cmd.ExecuteNonQuery();
con.Close();
return rows;
}
/// <summary>
/// 查询,返回数据集
/// </summary>
/// <param name="sql"></param>
/// <returns></returns>
public static DataTable GetDataTable(string sql)
{
SqlConnection con = new SqlConnection(conStr);
con.Open();
DataTable dt = new DataTable();
SqlDataAdapter dap = new SqlDataAdapter(sql, con);
dap.Fill(dt);
con.Close();
return dt;
}
}
}