C# - 通过DataGridView实现对Oracle的操作

2019-11-13 来源: Jeremy.Wu 发布在  https://www.cnblogs.com/jeremywucnblog/p/11848235.html

前言

通过VS2019建立WinFrm应用程序,搭建桌面程序后,通过封装数据库操作OracleHelper类和业务逻辑操作OracleSQL类,进而通过DataGridView实现对Oracle数据表的增删改查功能。

WinFrm桌面搭建

主要控件:GroupBox、Label、TextBox、Button和DataGridView。

如下图:

NuGet程序包管理 - Oracle.ManagedDataAccess.dll安装

通过NuGet程序包管理界面安装Oracle.managedDataAccess程序包,注意这里我安装的是12.1.24版本,高版本的不好用(坑太多,自己体会)。

安装完成后,Oracle.managedDataAccess.dll文件将会自动添加到Bin文件夹下。

核心代码

Oracle数据库操作封装类OracleHelper.cs

请看代码:

 using System;
 using System.Data;
 using System.Collections.Generic;
 using System.Configuration;
 using Oracle.ManagedDataAccess.Client;
 using System.Text;
 using System.IO;

 /// <summary>
 /// Oracle数据库操作类
 /// </summary>
 public static class OracleHelper
 {
     //连接字符串
     public static string oraConnStr = "Data Source=(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=172.0.0.0)(PORT=1521))(CONNECT_DATA=(SERVICE_NAME=testdb)));Persist Security Info=True;User ID=sa;Password=123";

     #region Oracle数据库操作通用方法
     /// <summary>
     /// 测试数据库连接是否正常
     /// </summary>
     /// <param name="strConn"></param>
     /// <returns></returns>
     public static bool CheckOracleConnect(string strConn)
     {
         try
         {
             OracleConnection conn = new OracleConnection();
             conn.ConnectionString = strConn;
             conn.Open();
             return true;
         }
         catch
         {
             return false;
         }
     }

     /// <summary>
     /// 执行数据库非查询操作,返回受影响的行数
     /// </summary>
     /// <param name="connectionString">数据库连接字符串</param>
     /// <param name="cmdType">命令的类型</param>
     /// <param name="cmdText">Oracle存储过程名称或PL/SQL命令</param>
     /// <param name="cmdParms">命令参数集合</param>
     /// <returns>当前查询操作影响的数据行数</returns>
     public static int ExecuteNonQuery(string connectionString, CommandType cmdType, string cmdText, params OracleParameter[] cmdParms)
     {
         OracleCommand cmd = new OracleCommand();
         using (OracleConnection conn = new OracleConnection(connectionString))
         {
             PrepareCommand(cmd, conn, null, cmdType, cmdText, cmdParms);
             int val = cmd.ExecuteNonQuery();
             cmd.Parameters.Clear();
             return val;
         }
     }

     /// <summary>
     /// 执行数据库事务非查询操作,返回受影响的行数
     /// </summary>
     /// <param name="transaction">数据库事务对象</param>
     /// <param name="cmdType">Command类型</param>
     /// <param name="cmdText">Oracle存储过程名称或PL/SQL命令</param>
     /// <param name="cmdParms">命令参数集合</param>
     /// <returns>当前事务查询操作影响的数据行数</returns>
     public static int ExecuteNonQuery(OracleTransaction trans, CommandType cmdType, string cmdText, params OracleParameter[] cmdParms)
     {
         OracleCommand cmd = new OracleCommand();
         PrepareCommand(cmd, trans.Connection, trans, cmdType, cmdText, cmdParms);
         int val = cmd.ExecuteNonQuery();
         cmd.Parameters.Clear();
         return val;
     }

     /// <summary>
     /// 执行数据库非查询操作,返回受影响的行数
     /// </summary>
     /// <param name="connection">Oracle数据库连接对象</param>
     /// <param name="cmdType">Command类型</param>
     /// <param name="cmdText">Oracle存储过程名称或PL/SQL命令</param>
     /// <param name="cmdParms">命令参数集合</param>
     /// <returns>当前查询操作影响的数据行数</returns>
     public static int ExecuteNonQuery(OracleConnection connection, CommandType cmdType, string cmdText, params OracleParameter[] cmdParms)
     {
         if (connection == null)
             throw new ArgumentNullException("当前数据库连接不存在");
         OracleCommand cmd = new OracleCommand();
         PrepareCommand(cmd, connection, null, cmdType, cmdText, cmdParms);
         int val = cmd.ExecuteNonQuery();
         cmd.Parameters.Clear();
         return val;
     }

     /// <summary>
     /// 执行数据库查询操作,返回OracleDataReader类型的内存结果集
     /// </summary>
     /// <param name="connectionString">数据库连接字符串</param>
     /// <param name="cmdType">命令的类型</param>
     /// <param name="cmdText">Oracle存储过程名称或PL/SQL命令</param>
     /// <param name="cmdParms">命令参数集合</param>
     /// <returns>当前查询操作返回的OracleDataReader类型的内存结果集</returns>
     public static OracleDataReader ExecuteReader(string connectionString, CommandType cmdType, string cmdText, params OracleParameter[] cmdParms)
     {
         OracleCommand cmd = new OracleCommand();
         OracleConnection conn = new OracleConnection(connectionString);
         try
         {
             PrepareCommand(cmd, conn, null, cmdType, cmdText, cmdParms);
             OracleDataReader reader = cmd.ExecuteReader(CommandBehavior.CloseConnection);
             cmd.Parameters.Clear();
             return reader;
         }
         catch
         {
             cmd.Dispose();
             conn.Close();
             throw;
         }
     }

     /// <summary>
     /// 执行数据库查询操作,返回DataSet类型的结果集
     /// </summary>
     /// <param name="connectionString">数据库连接字符串</param>
     /// <param name="cmdType">命令的类型</param>
     /// <param name="cmdText">Oracle存储过程名称或PL/SQL命令</param>
     /// <param name="cmdParms">命令参数集合</param>
     /// <returns>当前查询操作返回的DataSet类型的结果集</returns>
     public static DataSet ExecuteDataSet(string connectionString, CommandType cmdType, string cmdText, params OracleParameter[] cmdParms)
     {
         OracleCommand cmd = new OracleCommand();
         OracleConnection conn = new OracleConnection(connectionString);
         DataSet ds = null;
         try
         {
             PrepareCommand(cmd, conn, null, cmdType, cmdText, cmdParms);
             OracleDataAdapter adapter = new OracleDataAdapter();
             adapter.SelectCommand = cmd;
             ds = new DataSet();
             adapter.Fill(ds);
             cmd.Parameters.Clear();
         }
         catch
         {
             throw;
         }
         finally
         {
             cmd.Dispose();
             conn.Close();
             conn.Dispose();
         }

         return ds;
     }

     /// <summary>
     /// 执行数据库查询操作,返回DataTable类型的结果集
     /// </summary>
     /// <param name="connectionString">数据库连接字符串</param>
     /// <param name="cmdType">命令的类型</param>
     /// <param name="cmdText">Oracle存储过程名称或PL/SQL命令</param>
     /// <param name="cmdParms">命令参数集合</param>
     /// <returns>当前查询操作返回的DataTable类型的结果集</returns>
     public static DataTable ExecuteDataTable(string connectionString, CommandType cmdType, string cmdText, params OracleParameter[] cmdParms)
     {
         OracleCommand cmd = new OracleCommand();
         OracleConnection conn = new OracleConnection(connectionString);
         DataTable dt = null;

         try
         {
             PrepareCommand(cmd, conn, null, cmdType, cmdText, cmdParms);
             OracleDataAdapter adapter = new OracleDataAdapter();
             adapter.SelectCommand = cmd;
             dt = new DataTable();
             adapter.Fill(dt);
             cmd.Parameters.Clear();
         }
         catch
         {
             throw;
         }
         finally
         {
             cmd.Dispose();
             conn.Close();
             conn.Dispose();
         }

         return dt;
     }

     /// <summary>
     /// 执行数据库查询操作,返回结果集中位于第一行第一列的Object类型的值
     /// </summary>
     /// <param name="connectionString">数据库连接字符串</param>
     /// <param name="cmdType">命令的类型</param>
     /// <param name="cmdText">Oracle存储过程名称或PL/SQL命令</param>
     /// <param name="cmdParms">命令参数集合</param>
     /// <returns>当前查询操作返回的结果集中位于第一行第一列的Object类型的值</returns>
     public static object ExecuteScalar(string connectionString, CommandType cmdType, string cmdText, params OracleParameter[] cmdParms)
     {
         OracleCommand cmd = new OracleCommand();
         OracleConnection conn = new OracleConnection(connectionString);
         object result = null;
         try
         {
             PrepareCommand(cmd, conn, null, cmdType, cmdText, cmdParms);
             result = cmd.ExecuteScalar();
             cmd.Parameters.Clear();
         }
         catch
         {
             throw;
         }
         finally
         {
             cmd.Dispose();
             conn.Close();
             conn.Dispose();
         }

         return result;
     }

     ///    <summary>
     ///    执行数据库事务查询操作,返回结果集中位于第一行第一列的Object类型的值
     ///    </summary>
     ///    <param name="trans">一个已存在的数据库事务对象</param>
     ///    <param name="commandType">命令类型</param>
     ///    <param name="commandText">Oracle存储过程名称或PL/SQL命令</param>
     ///    <param name="cmdParms">命令参数集合</param>
     ///    <returns>当前事务查询操作返回的结果集中位于第一行第一列的Object类型的值</returns>
     public static object ExecuteScalar(OracleTransaction trans, CommandType cmdType, string cmdText, params OracleParameter[] cmdParms)
     {
         if (trans == null)
             throw new ArgumentNullException("当前数据库事务不存在");
         OracleConnection conn = trans.Connection;
         if (conn == null)
             throw new ArgumentException("当前事务所在的数据库连接不存在");

         OracleCommand cmd = new OracleCommand();
         object result = null;

         try
         {
             PrepareCommand(cmd, conn, trans, cmdType, cmdText, cmdParms);
             result = cmd.ExecuteScalar();
             cmd.Parameters.Clear();
         }
         catch
         {
             throw;
         }
         finally
         {
             trans.Dispose();
             cmd.Dispose();
             conn.Close();
             conn.Dispose();
         }

         return result;
     }

     /// <summary>
     /// 执行数据库查询操作,返回结果集中位于第一行第一列的Object类型的值
     /// </summary>
     /// <param name="conn">数据库连接对象</param>
     /// <param name="cmdType">Command类型</param>
     /// <param name="cmdText">Oracle存储过程名称或PL/SQL命令</param>
     /// <param name="cmdParms">命令参数集合</param>
     /// <returns>当前查询操作返回的结果集中位于第一行第一列的Object类型的值</returns>
     public static object ExecuteScalar(OracleConnection conn, CommandType cmdType, string cmdText, params OracleParameter[] cmdParms)
     {
         if (conn == null) throw new ArgumentException("当前数据库连接不存在");
         OracleCommand cmd = new OracleCommand();
         object result = null;

         try
         {
             PrepareCommand(cmd, conn, null, cmdType, cmdText, cmdParms);
             result = cmd.ExecuteScalar();
             cmd.Parameters.Clear();
         }
         catch
         {
             throw;
         }
         finally
         {
             cmd.Dispose();
             conn.Close();
             conn.Dispose();
         }

         return result;
     }

     /// <summary>
     /// 执行数据库命令前的准备工作
     /// </summary>
     /// <param name="cmd">Command对象</param>
     /// <param name="conn">数据库连接对象</param>
     /// <param name="trans">事务对象</param>
     /// <param name="cmdType">Command类型</param>
     /// <param name="cmdText">Oracle存储过程名称或PL/SQL命令</param>
     /// <param name="cmdParms">命令参数集合</param>
     private static void PrepareCommand(OracleCommand cmd, OracleConnection conn, OracleTransaction trans, CommandType cmdType, string cmdText, OracleParameter[] cmdParms)
     {
         if (conn.State != ConnectionState.Open)
             conn.Open();

         cmd.Connection = conn;
         cmd.CommandText = cmdText;

         if (trans != null)
             cmd.Transaction = trans;

         cmd.CommandType = cmdType;

         if (cmdParms != null)
         {
             foreach (OracleParameter parm in cmdParms)
                 cmd.Parameters.Add(parm);
         }
     }

     /// <summary>
     /// 将.NET日期时间类型转化为Oracle兼容的日期时间格式字符串
     /// </summary>
     /// <param name="date">.NET日期时间类型对象</param>
     /// <returns>Oracle兼容的日期时间格式字符串(如该字符串:TO_DATE('2007-12-1','YYYY-MM-DD'))</returns>
     public static string GetOracleDateFormat(DateTime date)
     {
         return "TO_DATE('" + date.ToString("yyyy-M-dd") + "','YYYY-MM-DD')";
     }

     /// <summary>
     /// 将.NET日期时间类型转化为Oracle兼容的日期格式字符串
     /// </summary>
     /// <param name="date">.NET日期时间类型对象</param>
     /// <param name="format">Oracle日期时间类型格式化限定符</param>
     /// <returns>Oracle兼容的日期时间格式字符串(如该字符串:TO_DATE('2007-12-1','YYYY-MM-DD'))</returns>
     public static string GetOracleDateFormat(DateTime date, string format)
     {
         if (format == null || format.Trim() == "") format = "YYYY-MM-DD";
         return "TO_DATE('" + date.ToString("yyyy-M-dd") + "','" + format + "')";
     }

     /// <summary>
     /// 将指定的关键字处理为模糊查询时的合法参数值
     /// </summary>
     /// <param name="source">待处理的查询关键字</param>
     /// <returns>过滤后的查询关键字</returns>
     public static string HandleLikeKey(string source)
     {
         if (source == null || source.Trim() == "") return null;

         source = source.Replace("[", "[]]");
         source = source.Replace("_", "[_]");
         source = source.Replace("%", "[%]");

         return ("%" + source + "%");
     }
     #endregion
 }

业务逻辑封装类OracleSQL.cs

请看代码:

 using System;
 using System.Collections.Generic;
 using System.Linq;
 using System.Text;
 using System.Threading.Tasks;

 namespace _004___VS2019连接Oracle数据库并实现数据库表的增删改查
 {
     /// <summary>
     /// 业务逻辑类,主要封装SQL语句
     /// </summary>
     class OracleSQL
     {
         // 查询表数据
         public static string GetWZJPerson = "select * from wzj_person where name =:name order by syid";
         // 模糊查询表数据
         public static string GerWZJPersonLike = "select * from wzj_person where name like :name order by syid";
         // 根据syid删除数据
         public static string DeleteWZJPersonData = "delete from wzj_person where syid = :syid";
         // 添加数据
         public static string InsertWZJPersonData = "insert into wzj_person(name, age, birthday, syid, ptoneno, workno, address) values(:name, :age, :birthday, :syid, :ptoneno, :workno, :address) ";
         // 更新数据
         public static string UpdateWZJPersonData = "update wzj_person set name=:name, age=:age, birthday=:birthday, ptoneno=:ptoneno, workno=:workno, address=:address where syid =:syid";
     }
 }

增删改查

         /// <summary>
         /// 启用编辑、添加
         /// </summary>
         /// <param name="sender"></param>
         /// <param name="e"></param>
         private void btnAdd_Click(object sender, EventArgs e)
         {
             // 启用编辑
             dgvMain.ReadOnly = false;
             // 滚动到最后一行
             ;
             // 选中最后一行
             ].Selected = true;
         }

         /// <summary>
         /// 删除某一行,同步删除数据库表
         /// </summary>
         /// <param name="sender"></param>
         /// <param name="e"></param>
         private void btnDelete_Click(object sender, EventArgs e)
         {
             // 获取选中行
             int strRowIdex = dgvMain.CurrentCell.RowIndex;
             // 获取strSyID
             string strSyID = dgvMain.Rows[strRowIdex].Cells["SyID"].Value.ToString();
             // 创建参数对象
             OracleParameter[] param = new OracleParameter[] { new OracleParameter(":SyID", OracleDbType.Varchar2) };
             param[].Value = strSyID;
             // 删除数据库表
             int i = OracleHelper.ExecuteNonQuery(OracleHelper.oraConnStr, CommandType.Text, OracleSQL.DeleteWZJPersonData, param);
             // 移除选中行
             dgvMain.Rows.RemoveAt(strRowIdex);
             // 消息提示
             MessageBox.Show("删除成功!", "提示");

         }

         /// <summary>
         /// 保存添加的数据
         /// </summary>
         /// <param name="sender"></param>
         /// <param name="e"></param>
         private void btnPost_Click(object sender, EventArgs e)
         {
             // 获取选中行
             int strRowIdex = dgvMain.CurrentCell.RowIndex;
             // 创建参数对象 name, age, birthday, syid, ptoneno, workno, address
             OracleParameter[] param = new OracleParameter[] {
                 new OracleParameter(":name", OracleDbType.Varchar2),
                 new OracleParameter(":age", OracleDbType.Int32),
                 new OracleParameter(":birthday", OracleDbType.Date),
                 new OracleParameter(":syid", OracleDbType.Varchar2),
                 new OracleParameter(":ptoneno", OracleDbType.Varchar2),
                 new OracleParameter(":workno", OracleDbType.Varchar2),
                 new OracleParameter(":address", OracleDbType.Varchar2)
             };
             param[].Value = dgvMain.Rows[strRowIdex].Cells["name"].Value;
             param[].Value = dgvMain.Rows[strRowIdex].Cells["age"].Value;
             param[].Value = dgvMain.Rows[strRowIdex].Cells["birthday"].Value;
             param[].Value = dgvMain.Rows[strRowIdex].Cells["syid"].Value;
             param[].Value = dgvMain.Rows[strRowIdex].Cells["ptoneno"].Value;
             param[].Value = dgvMain.Rows[strRowIdex].Cells["workno"].Value;
             param[].Value = dgvMain.Rows[strRowIdex].Cells["address"].Value;

             // 插入数据库表
             int i = OracleHelper.ExecuteNonQuery(OracleHelper.oraConnStr, CommandType.Text, OracleSQL.InsertWZJPersonData, param);
             // 消息提示
             MessageBox.Show("保存成功!", "提示");
         }

         /// <summary>
         /// 更新DataGridView选中行数据
         /// </summary>
         /// <param name="sender"></param>
         /// <param name="e"></param>
         private void btnUpdate_Click(object sender, EventArgs e)
         {
             // 获取选中行
             int strRowIdex = dgvMain.CurrentCell.RowIndex;
             // 创建参数对象 name, age, birthday, syid, ptoneno, workno, address
             OracleParameter[] param = new OracleParameter[] {
                 new OracleParameter(":name", OracleDbType.Varchar2),
                 new OracleParameter(":age", OracleDbType.Int32),
                 new OracleParameter(":birthday", OracleDbType.Date),
                 new OracleParameter(":ptoneno", OracleDbType.Varchar2),
                 new OracleParameter(":workno", OracleDbType.Varchar2),
                 new OracleParameter(":address", OracleDbType.Varchar2),
                 new OracleParameter(":syid", OracleDbType.Varchar2)
             };
             param[].Value = dgvMain.Rows[strRowIdex].Cells["name"].Value;
             param[].Value = dgvMain.Rows[strRowIdex].Cells["age"].Value;
             param[].Value = dgvMain.Rows[strRowIdex].Cells["birthday"].Value;
             param[].Value = dgvMain.Rows[strRowIdex].Cells["ptoneno"].Value;
             param[].Value = dgvMain.Rows[strRowIdex].Cells["workno"].Value;
             param[].Value = dgvMain.Rows[strRowIdex].Cells["address"].Value;
             param[].Value = dgvMain.Rows[strRowIdex].Cells["syid"].Value;

             // 更新数据库表
             int i = OracleHelper.ExecuteNonQuery(OracleHelper.oraConnStr, CommandType.Text, OracleSQL.UpdateWZJPersonData, param);
             // 消息提示
             MessageBox.Show("更新成功!", "提示");
         }

运行效果

相关文章