C# - VS2019 通过DataGridView实现对Oracle数据表的增删改查

痴心易碎 提交于 2019-12-04 08:24:53

前言

通过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

请看代码:

  1 using System;
  2 using System.Data;
  3 using System.Collections.Generic;
  4 using System.Configuration;
  5 using Oracle.ManagedDataAccess.Client;
  6 using System.Text;
  7 using System.IO;
  8 
  9 /// <summary>  
 10 /// Oracle数据库操作类  
 11 /// </summary>  
 12 public static class OracleHelper
 13 {
 14     //连接字符串
 15     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";
 16 
 17     #region Oracle数据库操作通用方法
 18     /// <summary>
 19     /// 测试数据库连接是否正常
 20     /// </summary>
 21     /// <param name="strConn"></param>
 22     /// <returns></returns>
 23     public static bool CheckOracleConnect(string strConn)
 24     {
 25         try
 26         {
 27             OracleConnection conn = new OracleConnection();
 28             conn.ConnectionString = strConn;
 29             conn.Open();
 30             return true;
 31         }
 32         catch
 33         {
 34             return false;
 35         }
 36     }
 37 
 38     /// <summary>  
 39     /// 执行数据库非查询操作,返回受影响的行数  
 40     /// </summary>  
 41     /// <param name="connectionString">数据库连接字符串</param>
 42     /// <param name="cmdType">命令的类型</param>
 43     /// <param name="cmdText">Oracle存储过程名称或PL/SQL命令</param>  
 44     /// <param name="cmdParms">命令参数集合</param>  
 45     /// <returns>当前查询操作影响的数据行数</returns>  
 46     public static int ExecuteNonQuery(string connectionString, CommandType cmdType, string cmdText, params OracleParameter[] cmdParms)
 47     {
 48         OracleCommand cmd = new OracleCommand();
 49         using (OracleConnection conn = new OracleConnection(connectionString))
 50         {
 51             PrepareCommand(cmd, conn, null, cmdType, cmdText, cmdParms);
 52             int val = cmd.ExecuteNonQuery();
 53             cmd.Parameters.Clear();
 54             return val;
 55         }
 56     }
 57 
 58     /// <summary>  
 59     /// 执行数据库事务非查询操作,返回受影响的行数  
 60     /// </summary>  
 61     /// <param name="transaction">数据库事务对象</param>  
 62     /// <param name="cmdType">Command类型</param>  
 63     /// <param name="cmdText">Oracle存储过程名称或PL/SQL命令</param>  
 64     /// <param name="cmdParms">命令参数集合</param>  
 65     /// <returns>当前事务查询操作影响的数据行数</returns>  
 66     public static int ExecuteNonQuery(OracleTransaction trans, CommandType cmdType, string cmdText, params OracleParameter[] cmdParms)
 67     {
 68         OracleCommand cmd = new OracleCommand();
 69         PrepareCommand(cmd, trans.Connection, trans, cmdType, cmdText, cmdParms);
 70         int val = cmd.ExecuteNonQuery();
 71         cmd.Parameters.Clear();
 72         return val;
 73     }
 74 
 75     /// <summary>  
 76     /// 执行数据库非查询操作,返回受影响的行数  
 77     /// </summary>  
 78     /// <param name="connection">Oracle数据库连接对象</param>  
 79     /// <param name="cmdType">Command类型</param>  
 80     /// <param name="cmdText">Oracle存储过程名称或PL/SQL命令</param>  
 81     /// <param name="cmdParms">命令参数集合</param>  
 82     /// <returns>当前查询操作影响的数据行数</returns>  
 83     public static int ExecuteNonQuery(OracleConnection connection, CommandType cmdType, string cmdText, params OracleParameter[] cmdParms)
 84     {
 85         if (connection == null)
 86             throw new ArgumentNullException("当前数据库连接不存在");
 87         OracleCommand cmd = new OracleCommand();
 88         PrepareCommand(cmd, connection, null, cmdType, cmdText, cmdParms);
 89         int val = cmd.ExecuteNonQuery();
 90         cmd.Parameters.Clear();
 91         return val;
 92     }
 93 
 94     /// <summary>  
 95     /// 执行数据库查询操作,返回OracleDataReader类型的内存结果集  
 96     /// </summary>  
 97     /// <param name="connectionString">数据库连接字符串</param>
 98     /// <param name="cmdType">命令的类型</param>
 99     /// <param name="cmdText">Oracle存储过程名称或PL/SQL命令</param>  
100     /// <param name="cmdParms">命令参数集合</param>  
101     /// <returns>当前查询操作返回的OracleDataReader类型的内存结果集</returns>  
102     public static OracleDataReader ExecuteReader(string connectionString, CommandType cmdType, string cmdText, params OracleParameter[] cmdParms)
103     {
104         OracleCommand cmd = new OracleCommand();
105         OracleConnection conn = new OracleConnection(connectionString);
106         try
107         {
108             PrepareCommand(cmd, conn, null, cmdType, cmdText, cmdParms);
109             OracleDataReader reader = cmd.ExecuteReader(CommandBehavior.CloseConnection);
110             cmd.Parameters.Clear();
111             return reader;
112         }
113         catch
114         {
115             cmd.Dispose();
116             conn.Close();
117             throw;
118         }
119     }
120 
121     /// <summary>  
122     /// 执行数据库查询操作,返回DataSet类型的结果集  
123     /// </summary>  
124     /// <param name="connectionString">数据库连接字符串</param>
125     /// <param name="cmdType">命令的类型</param>
126     /// <param name="cmdText">Oracle存储过程名称或PL/SQL命令</param>  
127     /// <param name="cmdParms">命令参数集合</param>  
128     /// <returns>当前查询操作返回的DataSet类型的结果集</returns>  
129     public static DataSet ExecuteDataSet(string connectionString, CommandType cmdType, string cmdText, params OracleParameter[] cmdParms)
130     {
131         OracleCommand cmd = new OracleCommand();
132         OracleConnection conn = new OracleConnection(connectionString);
133         DataSet ds = null;
134         try
135         {
136             PrepareCommand(cmd, conn, null, cmdType, cmdText, cmdParms);
137             OracleDataAdapter adapter = new OracleDataAdapter();
138             adapter.SelectCommand = cmd;
139             ds = new DataSet();
140             adapter.Fill(ds);
141             cmd.Parameters.Clear();
142         }
143         catch
144         {
145             throw;
146         }
147         finally
148         {
149             cmd.Dispose();
150             conn.Close();
151             conn.Dispose();
152         }
153 
154         return ds;
155     }
156 
157     /// <summary>  
158     /// 执行数据库查询操作,返回DataTable类型的结果集  
159     /// </summary>  
160     /// <param name="connectionString">数据库连接字符串</param>
161     /// <param name="cmdType">命令的类型</param>
162     /// <param name="cmdText">Oracle存储过程名称或PL/SQL命令</param>  
163     /// <param name="cmdParms">命令参数集合</param>  
164     /// <returns>当前查询操作返回的DataTable类型的结果集</returns>  
165     public static DataTable ExecuteDataTable(string connectionString, CommandType cmdType, string cmdText, params OracleParameter[] cmdParms)
166     {
167         OracleCommand cmd = new OracleCommand();
168         OracleConnection conn = new OracleConnection(connectionString);
169         DataTable dt = null;
170 
171         try
172         {
173             PrepareCommand(cmd, conn, null, cmdType, cmdText, cmdParms);
174             OracleDataAdapter adapter = new OracleDataAdapter();
175             adapter.SelectCommand = cmd;
176             dt = new DataTable();
177             adapter.Fill(dt);
178             cmd.Parameters.Clear();
179         }
180         catch
181         {
182             throw;
183         }
184         finally
185         {
186             cmd.Dispose();
187             conn.Close();
188             conn.Dispose();
189         }
190 
191         return dt;
192     }
193 
194     /// <summary>  
195     /// 执行数据库查询操作,返回结果集中位于第一行第一列的Object类型的值  
196     /// </summary>  
197     /// <param name="connectionString">数据库连接字符串</param>
198     /// <param name="cmdType">命令的类型</param>
199     /// <param name="cmdText">Oracle存储过程名称或PL/SQL命令</param>  
200     /// <param name="cmdParms">命令参数集合</param>  
201     /// <returns>当前查询操作返回的结果集中位于第一行第一列的Object类型的值</returns>  
202     public static object ExecuteScalar(string connectionString, CommandType cmdType, string cmdText, params OracleParameter[] cmdParms)
203     {
204         OracleCommand cmd = new OracleCommand();
205         OracleConnection conn = new OracleConnection(connectionString);
206         object result = null;
207         try
208         {
209             PrepareCommand(cmd, conn, null, cmdType, cmdText, cmdParms);
210             result = cmd.ExecuteScalar();
211             cmd.Parameters.Clear();
212         }
213         catch
214         {
215             throw;
216         }
217         finally
218         {
219             cmd.Dispose();
220             conn.Close();
221             conn.Dispose();
222         }
223 
224         return result;
225     }
226 
227     ///    <summary>  
228     ///    执行数据库事务查询操作,返回结果集中位于第一行第一列的Object类型的值  
229     ///    </summary>  
230     ///    <param name="trans">一个已存在的数据库事务对象</param>  
231     ///    <param name="commandType">命令类型</param>  
232     ///    <param name="commandText">Oracle存储过程名称或PL/SQL命令</param>  
233     ///    <param name="cmdParms">命令参数集合</param>  
234     ///    <returns>当前事务查询操作返回的结果集中位于第一行第一列的Object类型的值</returns>  
235     public static object ExecuteScalar(OracleTransaction trans, CommandType cmdType, string cmdText, params OracleParameter[] cmdParms)
236     {
237         if (trans == null)
238             throw new ArgumentNullException("当前数据库事务不存在");
239         OracleConnection conn = trans.Connection;
240         if (conn == null)
241             throw new ArgumentException("当前事务所在的数据库连接不存在");
242 
243         OracleCommand cmd = new OracleCommand();
244         object result = null;
245 
246         try
247         {
248             PrepareCommand(cmd, conn, trans, cmdType, cmdText, cmdParms);
249             result = cmd.ExecuteScalar();
250             cmd.Parameters.Clear();
251         }
252         catch
253         {
254             throw;
255         }
256         finally
257         {
258             trans.Dispose();
259             cmd.Dispose();
260             conn.Close();
261             conn.Dispose();
262         }
263 
264         return result;
265     }
266 
267     /// <summary>  
268     /// 执行数据库查询操作,返回结果集中位于第一行第一列的Object类型的值  
269     /// </summary>  
270     /// <param name="conn">数据库连接对象</param>  
271     /// <param name="cmdType">Command类型</param>  
272     /// <param name="cmdText">Oracle存储过程名称或PL/SQL命令</param>  
273     /// <param name="cmdParms">命令参数集合</param>  
274     /// <returns>当前查询操作返回的结果集中位于第一行第一列的Object类型的值</returns>  
275     public static object ExecuteScalar(OracleConnection conn, CommandType cmdType, string cmdText, params OracleParameter[] cmdParms)
276     {
277         if (conn == null) throw new ArgumentException("当前数据库连接不存在");
278         OracleCommand cmd = new OracleCommand();
279         object result = null;
280 
281         try
282         {
283             PrepareCommand(cmd, conn, null, cmdType, cmdText, cmdParms);
284             result = cmd.ExecuteScalar();
285             cmd.Parameters.Clear();
286         }
287         catch
288         {
289             throw;
290         }
291         finally
292         {
293             cmd.Dispose();
294             conn.Close();
295             conn.Dispose();
296         }
297 
298         return result;
299     }
300 
301     /// <summary>  
302     /// 执行数据库命令前的准备工作  
303     /// </summary>  
304     /// <param name="cmd">Command对象</param>  
305     /// <param name="conn">数据库连接对象</param>  
306     /// <param name="trans">事务对象</param>  
307     /// <param name="cmdType">Command类型</param>  
308     /// <param name="cmdText">Oracle存储过程名称或PL/SQL命令</param>  
309     /// <param name="cmdParms">命令参数集合</param>  
310     private static void PrepareCommand(OracleCommand cmd, OracleConnection conn, OracleTransaction trans, CommandType cmdType, string cmdText, OracleParameter[] cmdParms)
311     {
312         if (conn.State != ConnectionState.Open)
313             conn.Open();
314 
315         cmd.Connection = conn;
316         cmd.CommandText = cmdText;
317 
318         if (trans != null)
319             cmd.Transaction = trans;
320 
321         cmd.CommandType = cmdType;
322 
323         if (cmdParms != null)
324         {
325             foreach (OracleParameter parm in cmdParms)
326                 cmd.Parameters.Add(parm);
327         }
328     }
329 
330     /// <summary>  
331     /// 将.NET日期时间类型转化为Oracle兼容的日期时间格式字符串  
332     /// </summary>  
333     /// <param name="date">.NET日期时间类型对象</param>  
334     /// <returns>Oracle兼容的日期时间格式字符串(如该字符串:TO_DATE('2007-12-1','YYYY-MM-DD'))</returns>  
335     public static string GetOracleDateFormat(DateTime date)
336     {
337         return "TO_DATE('" + date.ToString("yyyy-M-dd") + "','YYYY-MM-DD')";
338     }
339 
340     /// <summary>  
341     /// 将.NET日期时间类型转化为Oracle兼容的日期格式字符串  
342     /// </summary>  
343     /// <param name="date">.NET日期时间类型对象</param>  
344     /// <param name="format">Oracle日期时间类型格式化限定符</param>  
345     /// <returns>Oracle兼容的日期时间格式字符串(如该字符串:TO_DATE('2007-12-1','YYYY-MM-DD'))</returns>  
346     public static string GetOracleDateFormat(DateTime date, string format)
347     {
348         if (format == null || format.Trim() == "") format = "YYYY-MM-DD";
349         return "TO_DATE('" + date.ToString("yyyy-M-dd") + "','" + format + "')";
350     }
351 
352     /// <summary>  
353     /// 将指定的关键字处理为模糊查询时的合法参数值  
354     /// </summary>  
355     /// <param name="source">待处理的查询关键字</param>  
356     /// <returns>过滤后的查询关键字</returns>  
357     public static string HandleLikeKey(string source)
358     {
359         if (source == null || source.Trim() == "") return null;
360 
361         source = source.Replace("[", "[]]");
362         source = source.Replace("_", "[_]");
363         source = source.Replace("%", "[%]");
364 
365         return ("%" + source + "%");
366     }
367     #endregion
368 }
View Code

业务逻辑封装类OracleSQL.cs

请看代码:

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 using System.Threading.Tasks;
 6 
 7 namespace _004___VS2019连接Oracle数据库并实现数据库表的增删改查
 8 {
 9     /// <summary>
10     /// 业务逻辑类,主要封装SQL语句
11     /// </summary>
12     class OracleSQL
13     {
14         // 查询表数据
15         public static string GetWZJPerson = "select * from wzj_person where name =:name order by syid";
16         // 模糊查询表数据
17         public static string GerWZJPersonLike = "select * from wzj_person where name like :name order by syid";
18         // 根据syid删除数据
19         public static string DeleteWZJPersonData = "delete from wzj_person where syid = :syid";
20         // 添加数据
21         public static string InsertWZJPersonData = "insert into wzj_person(name, age, birthday, syid, ptoneno, workno, address) values(:name, :age, :birthday, :syid, :ptoneno, :workno, :address) ";
22         // 更新数据
23         public static string UpdateWZJPersonData = "update wzj_person set name=:name, age=:age, birthday=:birthday, ptoneno=:ptoneno, workno=:workno, address=:address where syid =:syid";
24     }
25 }
View Code

 增删改查

  1         /// <summary>
  2         /// 启用编辑、添加
  3         /// </summary>
  4         /// <param name="sender"></param>
  5         /// <param name="e"></param>
  6         private void btnAdd_Click(object sender, EventArgs e)
  7         {
  8             // 启用编辑
  9             dgvMain.ReadOnly = false;
 10             // 滚动到最后一行
 11             this.dgvMain.FirstDisplayedScrollingRowIndex = this.dgvMain.Rows.Count - 1;
 12             // 选中最后一行
 13             this.dgvMain.Rows[this.dgvMain.Rows.Count - 1].Selected = true;
 14         }
 15 
 16         /// <summary>
 17         /// 删除某一行,同步删除数据库表
 18         /// </summary>
 19         /// <param name="sender"></param>
 20         /// <param name="e"></param>
 21         private void btnDelete_Click(object sender, EventArgs e)
 22         {
 23             // 获取选中行
 24             int strRowIdex = dgvMain.CurrentCell.RowIndex;
 25             // 获取strSyID
 26             string strSyID = dgvMain.Rows[strRowIdex].Cells["SyID"].Value.ToString();
 27             // 创建参数对象
 28             OracleParameter[] param = new OracleParameter[] { new OracleParameter(":SyID", OracleDbType.Varchar2) };
 29             param[0].Value = strSyID;
 30             // 删除数据库表
 31             int i = OracleHelper.ExecuteNonQuery(OracleHelper.oraConnStr, CommandType.Text, OracleSQL.DeleteWZJPersonData, param);
 32             // 移除选中行
 33             dgvMain.Rows.RemoveAt(strRowIdex);
 34             // 消息提示
 35             MessageBox.Show("删除成功!", "提示");
 36 
 37         }
 38 
 39         /// <summary>
 40         /// 保存添加的数据
 41         /// </summary>
 42         /// <param name="sender"></param>
 43         /// <param name="e"></param>
 44         private void btnPost_Click(object sender, EventArgs e)
 45         {
 46             // 获取选中行
 47             int strRowIdex = dgvMain.CurrentCell.RowIndex;
 48             // 创建参数对象 name, age, birthday, syid, ptoneno, workno, address
 49             OracleParameter[] param = new OracleParameter[] {
 50                 new OracleParameter(":name", OracleDbType.Varchar2),
 51                 new OracleParameter(":age", OracleDbType.Int32),
 52                 new OracleParameter(":birthday", OracleDbType.Date),
 53                 new OracleParameter(":syid", OracleDbType.Varchar2),
 54                 new OracleParameter(":ptoneno", OracleDbType.Varchar2),
 55                 new OracleParameter(":workno", OracleDbType.Varchar2),
 56                 new OracleParameter(":address", OracleDbType.Varchar2)
 57             };
 58             param[0].Value = dgvMain.Rows[strRowIdex].Cells["name"].Value;
 59             param[1].Value = dgvMain.Rows[strRowIdex].Cells["age"].Value;
 60             param[2].Value = dgvMain.Rows[strRowIdex].Cells["birthday"].Value;
 61             param[3].Value = dgvMain.Rows[strRowIdex].Cells["syid"].Value;
 62             param[4].Value = dgvMain.Rows[strRowIdex].Cells["ptoneno"].Value;
 63             param[5].Value = dgvMain.Rows[strRowIdex].Cells["workno"].Value;
 64             param[6].Value = dgvMain.Rows[strRowIdex].Cells["address"].Value;
 65 
 66             // 插入数据库表
 67             int i = OracleHelper.ExecuteNonQuery(OracleHelper.oraConnStr, CommandType.Text, OracleSQL.InsertWZJPersonData, param);
 68             // 消息提示
 69             MessageBox.Show("保存成功!", "提示");
 70         }
 71 
 72         /// <summary>
 73         /// 更新DataGridView选中行数据
 74         /// </summary>
 75         /// <param name="sender"></param>
 76         /// <param name="e"></param>
 77         private void btnUpdate_Click(object sender, EventArgs e)
 78         {
 79             // 获取选中行
 80             int strRowIdex = dgvMain.CurrentCell.RowIndex;
 81             // 创建参数对象 name, age, birthday, syid, ptoneno, workno, address
 82             OracleParameter[] param = new OracleParameter[] {
 83                 new OracleParameter(":name", OracleDbType.Varchar2),
 84                 new OracleParameter(":age", OracleDbType.Int32),
 85                 new OracleParameter(":birthday", OracleDbType.Date),
 86                 new OracleParameter(":ptoneno", OracleDbType.Varchar2),
 87                 new OracleParameter(":workno", OracleDbType.Varchar2),
 88                 new OracleParameter(":address", OracleDbType.Varchar2),
 89                 new OracleParameter(":syid", OracleDbType.Varchar2)
 90             };
 91             param[0].Value = dgvMain.Rows[strRowIdex].Cells["name"].Value;
 92             param[1].Value = dgvMain.Rows[strRowIdex].Cells["age"].Value;
 93             param[2].Value = dgvMain.Rows[strRowIdex].Cells["birthday"].Value;
 94             param[3].Value = dgvMain.Rows[strRowIdex].Cells["ptoneno"].Value;
 95             param[4].Value = dgvMain.Rows[strRowIdex].Cells["workno"].Value;
 96             param[5].Value = dgvMain.Rows[strRowIdex].Cells["address"].Value;
 97             param[6].Value = dgvMain.Rows[strRowIdex].Cells["syid"].Value;
 98 
 99             // 更新数据库表
100             int i = OracleHelper.ExecuteNonQuery(OracleHelper.oraConnStr, CommandType.Text, OracleSQL.UpdateWZJPersonData, param);
101             // 消息提示
102             MessageBox.Show("更新成功!", "提示");
103         }
View Code

运行效果

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!