using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.SqlClient;
using System.Data;
namespace SqlServerHelper
{
public class sqlServerHelper
{
private static SqlConnection conn;//连接对象
public static string dataTable;//定义连接的表
/// <summary>
/// 连接数据库
/// </summary>
/// <returns></returns>
static public bool Conn(string server, string database, string id, string pwd)
{
try
{
//定义连接地址
string str = $"Server={server};DataBase={database};User ID={id};Pwd={pwd}";
//创建连接对象
conn = new SqlConnection(str);
//打开连接
conn.Open();
return true;
}
catch (Exception e)
{
return false;
}
}
/// <summary>
/// 读取数据
/// </summary>
/// <returns></returns>
static public string ExistData(string id)
{
try
{
//创建执行对象
SqlCommand comm = new SqlCommand($"select * from dbo.dete where id={id}", conn);
//执行并返回结果
SqlDataReader sdr = comm.ExecuteReader();
while (sdr.Read())
{
return sdr.GetString(1);
}
return null;
}
catch (Exception e)
{
return null;
}
}
/// <summary>
/// 增加数据
/// </summary>
/// <returns></returns>
static public bool AddData(string id, string name)
{
try
{
string sql = $"insert into dbo.dete (id,name) values({id},{name})";
//创建执行对象
SqlCommand comm = new SqlCommand(sql, conn);
//调用通用数据访问类
int result = comm.ExecuteNonQuery(); //返回受影响的行数,执行数据库的增删改
if (result == 1)
return true;
else
return false;
}
catch (Exception e)
{
string s = e.Message;
return false;
}
}
/// <summary>
/// 删除数据
/// </summary>
/// <returns></returns>
static public bool DeteData(int id)
{
try
{
string sql = $"delete from dbo.dete where id={id}";
//创建执行对象
SqlCommand comm = new SqlCommand(sql, conn);
//调用通用数据访问类
int result = comm.ExecuteNonQuery(); //返回受影响的行数,执行数据库的增删改
if (result == 1)
return true;
else
return false;
}
catch (Exception e)
{
return false;
}
}
/// <summary>
/// 更新数据
/// </summary>
/// <returns></returns>
static public bool UpdateData(string name, string id)
{
try
{
string sql = $"update dbo.dete set name={name} where id={id}";
//创建执行对象
SqlCommand comm = new SqlCommand(sql, conn);
//调用通用数据访问类
int result = comm.ExecuteNonQuery(); //返回受影响的行数,执行数据库的增删改
if (result == 1)
return true;
else
return false;
}
catch (Exception e)
{
return false;
}
}
/// <summary>
/// 查询表名
/// </summary>
/// <returns></returns>
static public DataTable SearchTable()
{
try
{
DataTable db = new DataTable();
db.Columns.Add(new DataColumn("name", typeof(string)));
string sql = "select name from sysobjects where xtype='u'";
//创建执行对象
SqlCommand comm = new SqlCommand(sql, conn);
//执行并返回结果
SqlDataReader sdr = comm.ExecuteReader();
while (sdr.Read())
{
db.Rows.Add(sdr.GetString(0));
}
return db;
}
catch (Exception e)
{
string s = e.Message;
return null;
}
}
}
}
最近需要用到这个数据库,就写了一个类方便自己使用,主要就是实现数据库的增删改查四个功能还有读取当前数据库中所有表名的功能,亲测,嘎嘎好使
这个就是我表的一个格式,你们可以自己看着和代码里的属性对照一下,改成自己的
中国人不骗中国人,嘿嘿