View Code
using System;
using System.Data.SqlClient;
using System.Data;
namespace Test
{
class SQLHelper
{
//定义数据库连接实例
private static SqlConnection con = CreateCon();
//创建数据库连接静态方法
public static SqlConnection CreateCon()
{
return new SqlConnection("server=127.0.0.1;database=test;uid=sa;pwd=123456");
}
/// <summary>
/// 获取数据集
/// </summary>
/// <param name="sequal">数据库语句</param>
/// <param name="tableName">数据表名称</param>
/// <returns>返回数据集</returns>
public static DataSet ExecuteDataSet(string sequal, string tableName)
{
DataSet ds = new DataSet();
try
{
//打开数据库连接
con.Open();
//创建数据库适配器连接
SqlDataAdapter sda = new SqlDataAdapter(sequal, con);
//填充数据集
sda.Fill(ds, tableName);
//返回数据集
return ds;
}catch(Exception ex)
{
throw new Exception(ex.Message);
}
finally
{
con.Close();
}
}
/// <summary>
/// 执行数据库命令并返回影响条数
/// </summary>
/// <param name="sequal">数据库语句</param>
/// <returns>返回影响条数</returns>
public static int ExecuteNonQuery(string sequal)
{
try
{
con.Open();
//创建数据库操作命令
SqlCommand cmd = new SqlCommand(sequal, con);
//返回执行数据库影响条数
return cmd.ExecuteNonQuery();
}
catch (Exception ex1)
{
throw new Exception(ex1.Message);
}
finally
{
con.Close();
}
}
}
}
调用方法:
//绑定winfrom中的表格(DataGridView)
DataSet ds = SQLHelper.ExecuteDataSet("select * from t1", "tableName");
DataGridView1.DataSource = ds.Tables["tableName"];
//添加数据
string str0 = "添加";
int count0 = SQLHelper.ExecuteNonQuery("insert into t1 (name) values ('" + str0 + "')");
if (count0 > 0)
MessageBox.Show("添加了" + count0 + "条数据!");
//修改数据
string str1 = "修改";
int count1 = SQLHelper.ExecuteNonQuery("update t1 set name = '" + str1 + "'");
if (count0 > 0)
MessageBox.Show("修改了" + count1 + "条数据!");
//删除数据
int count2 = SQLHelper.ExecuteNonQuery("delete from t1");
if (count2 > 0)
MessageBox.Show("删除了" + count2 + "条数据!");