c# mysql 插入 和 查询_C#对数据库的操作(增删改查)
1、【在web.config文件中配置】
2、【連接字符串】
private static readonly string StrCon = ConfigurationManager.ConnectionStrings["sqlConnection"].ToString();
3、【查詢(xún)數(shù)據(jù)方法】
///
/// 查詢(xún)數(shù)據(jù)
///
/// 查詢(xún)語(yǔ)句
/// 參數(shù)
///
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("查詢(xún)數(shù)據(jù)異常"+ex.Message);
}
}
4、【更新數(shù)據(jù)方法】
///
/// 更新數(shù)據(jù)
///
/// 更新語(yǔ)句
/// 參數(shù)
///
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("更新數(shù)據(jù)異常"+ex.Message) ;
}
}
5、【刪除數(shù)據(jù)方法】
///
/// 刪除數(shù)據(jù)
///
/// 刪除語(yǔ)句
/// 參數(shù)
///
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("刪除數(shù)據(jù)異常"+ex.Message);
}
}
6、【添加數(shù)據(jù)方法】
///
/// 刪除數(shù)據(jù)
///
/// 刪除語(yǔ)句
/// 參數(shù)
///
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("添加數(shù)據(jù)異常"+ex.Message);
}
}
7、寫(xiě)個(gè)方法調(diào)用【查詢(xún)數(shù)據(jù)方法】,其他三個(gè)方法調(diào)用與此類(lèi)似
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;
}
總結(jié)
以上是生活随笔為你收集整理的c# mysql 插入 和 查询_C#对数据库的操作(增删改查)的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 母猫绝育手术多少钱啊?
- 下一篇: mysql一些常用操作_表的一些常用操作