CSharp数据库使用SqlCommand进行增,删,改,查询操作

C# 数据库使用SqlCommand进行增,删,改,查询操作
2010-11-08 11:16
using System;
using System.Collections.Generic;
using System.Text;

// We will make use of the SQL server
// provider, however it would also be
// permissible to make use of the ADO.NET
// factory pattern for greater flexibility.
using System.Data;
using System.Data.SqlClient;

namespace AutoLotConnectedLayer
{
public class InventoryDAL
{
#region Connection and Disconnection details.
// This member will be used by all methods.
private SqlConnection sqlCn = new SqlConnection();

public void OpenConnection(string connectionString)
{
sqlCn.ConnectionString = connectionString;
sqlCn.Open();
}
public void CloseConnection()
{
sqlCn.Close();
}
#endregion

#region Insert logic (both versions)
//public void InsertAuto(int id, string color, string make, string petName)
//{
// // Format and execute SQL statement.
// string sql = string.Format("Insert Into Inventory" +
// "(CarID, Make, Color, PetName) Values" +
// "('{0}', '{1}', '{2}', '{3}')", id, make, color, petName);
//
// // Execute using our connection.
// using(SqlCommand cmd = new SqlCommand(sql, this.sqlCn))
// {
// cmd.ExecuteNonQuery();
// }
//}

public void InsertAuto(int id, string color, string make, string petName)
{
// Note the 'placeholders' in the SQL query.
string sql = string.Format("Insert Into Inventory" +
"(CarID, Make, Color, PetName) Values" +
"(@CarID, @Make, @Color, @PetName)");

// This command will have internal parameters.
using (SqlCommand cmd = new SqlCommand(sql, this.sqlCn))
{
// Fill params collection.
SqlParameter param = new SqlParameter();
param.ParameterName = "@CarID";
param.Value = id;
param.SqlDbType = SqlDbType.Int;
cmd.Parameters.Add(param);

param = new SqlParameter();
param.ParameterName = "@Make";
param.Value = make;
param.SqlDbType = SqlDbType.Char;
param.Size = 10;
cmd.Parameters.Add(param);

param = new SqlParameter();
param.ParameterName = "@Color";
param.Value = color;
param.SqlDbType = SqlDbType.Char;
param.Size = 10;
cmd.Parameters.Add(param);

param = new SqlParameter();
param.ParameterName = "@PetName";
param.Value = petName;
param.SqlDbType = SqlDbType.Char;
param.Size = 10;
cmd.Parameters.Add(param);

cmd.ExecuteNonQuery();
}
}
#endregion

#region Delete logic
public void DeleteCar(int id)
{
// Get ID of car to delete, then do so.
string sql = string.Format("Delete from Inventory where CarID = '{0}'",
id);
using (SqlCommand cmd = new SqlCommand(sql, this.sqlCn))
{
try
{
cmd.ExecuteNonQuery();
}
catch (SqlException ex)
{
Exception error = new Exception("Sorry! That car is on order!", ex);
throw error;
}
}
}
#endregion

#region Update logic
public void UpdateCarPetName(int id, string newPetName)
{
// Get ID of car to modify and new pet name.
string sql =
string.Format("Update Inventory Set PetName = '{0}' Where CarID = '{1}'",
newPetName, id);
using (SqlCommand cmd = new SqlCommand(sql, this.sqlCn))
{
cmd.ExecuteNonQuery();
}
}


#endregion

#region Select logic
public DataTable GetAllInventory()
{
// This will hold the records.
DataTable inv = new DataTable();

// Prep command object.
string sql = "Select * From Inventory";
using (SqlCommand cmd = new SqlCommand(sql, this.sqlCn))
{
SqlDataReader dr = cmd.ExecuteReader();
// Fill the DataTable with data from the reader and clean up.
inv.Load(dr);
dr.Close();
}
return inv;
}
#endregion

#region Trigger stored proc logic
public string LookUpPetName(int carID)
{
string carPetName = string.Empty;

// Establish name of stored proc.
using (SqlCommand cmd = new SqlCommand("GetPetName", this.sqlCn))
{
cmd.CommandType = CommandType.StoredProcedure;

// Input param.
SqlParameter param = new SqlParameter();
param.ParameterName = "@carID";
param.SqlDbType = SqlDbType.Int;
param.Value = carID;
param.Direction = ParameterDirection.Input;
cmd.Parameters.Add(param);

// Output param.
param = new SqlParameter();
param.ParameterName = "@petName";
param.SqlDbType = SqlDbType.Char;
param.Size = 10;
param.Direction = ParameterDirection.Output;
cmd.Parameters.Add(param);

// Execute the stored proc.
cmd.ExecuteNonQuery();

// Return output param.
carPetName = ((string)cmd.Parameters["@petName"].Value).Trim();
}
return carPetName;
}
#endregion

#region Tx Method
// A new member of the InventoryDAL class.
public void ProcessCreditRisk(bool throwEx, int custID)
{
// First, look up current name based on customer ID.
string fName = string.Empty;
string lName = string.Empty;

SqlCommand cmdSelect = new SqlCommand(
string.Format("Select * from Customers where CustID = {0}", custID), sqlCn);
using (SqlDataReader dr = cmdSelect.ExecuteReader())
{
while (dr.Read())
{
fName = (string)dr["FirstName"];
lName = (string)dr["LastName"];
}
}

// Create command objects which represent each step of the operation.
SqlCommand cmdRemove = new SqlCommand(
string.Format("Delete from Customers where CustID = {0}", custID), sqlCn);

SqlCommand cmdInsert = new SqlCommand(string.Format("Insert Into CreditRisks" +
"(CustID, FirstName, LastName) Values" +
"({0}, '{1}', '{2}')", custID, fName, lName), sqlCn);

// We will get this from the Connection object.
SqlTransaction tx = null;
try
{
tx = sqlCn.BeginTransaction();

// Enlist the commands into this transaction.
cmdInsert.Transaction = tx;
cmdRemove.Transaction = tx;

// Execute the commands.
cmdInsert.ExecuteNonQuery();
cmdRemove.ExecuteNonQuery();

// Simulate error.
if (throwEx)
{
throw new ApplicationException("Sorry! Database error! Tx failed...");
}

// Commit it!
tx.Commit();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
// Any error will rollback transaction.
tx.Rollback();
}
}
#endregion
}
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
DataGridView 是 Windows 窗体中的一个控件,用于展示和编辑数据的表格。DataTable 是一个数据集中的一张表,用于存储和操作数据。DataGridView 和 DataTable 可以结合使用,对数据库进行操作。 首先,可以通过连接数据库并执行 SQL 查询语句,将查询结果存储在 DataTable 中。然后,将 DataTable 的数据绑定到 DataGridView 上,从而将查询结果展示在表格中。 ``` csharp SqlConnection connection = new SqlConnection(connectionString); DataTable dataTable = new DataTable(); try { string query = "SELECT * FROM 表名"; SqlCommand command = new SqlCommand(query, connection); SqlDataAdapter adapter = new SqlDataAdapter(command); connection.Open(); adapter.Fill(dataTable); dataGridView.DataSource = dataTable; } catch (Exception ex) { MessageBox.Show("查询出错:" + ex.Message); } finally { connection.Close(); } ``` 其次,可以对 DataGridView 中的数据进行操作。通过修 DataTable 中的数据,并使用 SqlDataAdapter 更新数据库的数据。 ``` csharp DataRow newRow = dataTable.NewRow(); // 设置 newRow 的值 dataTable.Rows.Add(newRow); // 添加新行 DataRow row = dataTable.Rows[0]; // 修 row 的值 row.Delete(); // 除行 try { string updateQuery = "UPDATE 表名 SET 列名 = '新值' WHERE 条件"; SqlCommand updateCommand = new SqlCommand(updateQuery, connection); SqlDataAdapter adapter = new SqlDataAdapter(); adapter.UpdateCommand = updateCommand; int rowsAffected = adapter.Update(dataTable); } catch (Exception ex) { MessageBox.Show("更新出错:" + ex.Message); } finally { connection.Close(); } ``` 最后,可以通过 DataGridView 的筛选功能进行数据的查询。只需要在 DataGridView 绑定的 DataTable 上使用 Select 方法进行查询,并将查询结果重新绑定到 DataGridView 上即可。 ``` csharp try { DataRow[] rows = dataTable.Select("列名 = '值'"); DataTable queryResult = rows.CopyToDataTable(); dataGridView.DataSource = queryResult; } catch (Exception ex) { MessageBox.Show("查询出错:" + ex.Message); } ``` 使用 DataGridView 和 DataTable 对数据库进行查,可以方便地操作和展示数据,提升用户的数据交互体验。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值