数据库小工具(C#)

  在编写有关数据库方面的C#程序时,经常需要知道数据库的表中各字段的以下信息:
  1. 用于OracleParameter(或SqlParameter,...)中的字段和属性的数据库特定的数据类型。
  2. 其对应的.NET数据类型。
  如下面的程序片断所示:

None.gif using  (OracleConnection conn  =   new  OracleConnection(Pub.ConnString))
ExpandedBlockStart.gifContractedBlock.gif
dot.gif {
InBlock.gif  conn.Open();
InBlock.gif  OracleCommand comm 
= new OracleCommand(
InBlock.gif    
"SELECT trdate,txcode,drcrf,amount,balance,tellerno,txnote,zoneno,nodeno FROM detail "+
InBlock.gif    
"WHERE accno=:accno AND currtype=:currtype ORDER BY accno,currtype,trdate,seqno", conn);
InBlock.gif  comm.Parameters.Add(
"accno", OracleDbType.Int64).Value = long.Parse(acc.Substring(4,13));
InBlock.gif  comm.Parameters.Add(
"currtype", OracleDbType.Int16).Value = curr;
InBlock.gif  
using (OracleDataReader r = comm.ExecuteReader())
ExpandedSubBlockStart.gifContractedSubBlock.gif  
dot.gif{
InBlock.gif    
for (cnt = 0; r.Read(); cnt++)
ExpandedSubBlockStart.gifContractedSubBlock.gif    
dot.gif{
InBlock.gif      DataRow dr 
= dt.NewRow();
InBlock.gif      dr[
"TrDate"= r.GetDateTime(0);
InBlock.gif      dr[
"Txcode"= r.GetInt32(1);
InBlock.gif      dr[
"Drcrf"= IcbcEtc.GetDrcrfString(r.GetInt16(2));
InBlock.gif      dr[
"Amount"= r.GetInt64(3/ R;
InBlock.gif      dr[
"Balance"= r.GetInt64(4/ R;
InBlock.gif      dr[
"Tellerno"= r.GetInt32(5);
InBlock.gif      dr[
"TxNote"= r.GetString(6);
InBlock.gif      dr[
"Zoneno"= r.GetInt32(7);
InBlock.gif      dr[
"Nodeno"= r.GetInt32(8);
InBlock.gif      dr[
"Txname"= DbTrxCode.GetNewName((int)dr["Txcode"]);
InBlock.gif      dt.Rows.Add(dr);
ExpandedSubBlockEnd.gif    }

ExpandedSubBlockEnd.gif  }

ExpandedBlockEnd.gif}

None.gif

  为此,我编写了一个小工具,其应用示例如下:
odpnet-01.PNG
  这里是源程序(ODP.NET版),需要下载“Oracle Data Provider for .NET”,其命名空间是: Oracle.DataAccess.Client。

None.gif using  System;
None.gif
using  System.Data;
None.gif
using  System.Text;
None.gif
using  System.Windows.Forms;
None.gif
using  System.Drawing;
None.gif
using  Oracle.DataAccess.Client;
None.gif
None.gif
namespace  Skyiv.Util.Odpnet
ExpandedBlockStart.gifContractedBlock.gif
dot.gif {
InBlock.gif  
class OdpnetDlg : Form
ExpandedSubBlockStart.gifContractedSubBlock.gif  
dot.gif{
InBlock.gif    Label    lblTable;
InBlock.gif    TextBox  tbxConn;
InBlock.gif    TextBox  tbxSql;
InBlock.gif    TextBox  tbxMsg;
InBlock.gif    Button   btnSubmit;
InBlock.gif    CheckBox chkStru;
InBlock.gif    DataGrid dgOut;
InBlock.gif    
string strConn = "Data Source=ora-m38;User ID=test;Password=p@ssw0rd";
InBlock.gif
InBlock.gif    
public OdpnetDlg()
ExpandedSubBlockStart.gifContractedSubBlock.gif    
dot.gif{
InBlock.gif      SuspendLayout();
InBlock.gif      
InBlock.gif      btnSubmit 
= new Button();
InBlock.gif      btnSubmit.Text 
= "执行";
InBlock.gif      btnSubmit.Location 
= new Point(10420);
InBlock.gif      btnSubmit.Size 
= new Size(6024);
InBlock.gif      btnSubmit.Click 
+= new EventHandler(Submit_Click);
InBlock.gif      btnSubmit.Anchor 
= (AnchorStyles.Bottom | AnchorStyles.Left);
InBlock.gif
InBlock.gif      chkStru 
= new CheckBox();
InBlock.gif      chkStru.Text 
= "结构";
InBlock.gif      chkStru.Location 
= new Point(80420);
InBlock.gif      chkStru.Size 
= new Size(6024);
InBlock.gif      chkStru.Anchor 
= (AnchorStyles.Bottom | AnchorStyles.Left);
InBlock.gif
InBlock.gif      lblTable 
= new Label();
InBlock.gif      lblTable.Text 
= "数据源";
InBlock.gif      lblTable.Location 
= new Point(12460);
InBlock.gif      lblTable.Size 
= new Size(7024);
InBlock.gif      lblTable.Anchor 
= (AnchorStyles.Bottom | AnchorStyles.Left);
InBlock.gif
InBlock.gif      tbxConn 
= new TextBox();
InBlock.gif      tbxConn.Text 
= strConn;
InBlock.gif      tbxConn.Location 
= new Point(83456);
InBlock.gif      tbxConn.Size 
= new Size(62620);
InBlock.gif      tbxConn.Anchor 
= (AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Right);
InBlock.gif
InBlock.gif      tbxSql 
= new TextBox();
InBlock.gif      tbxSql.Text 
= "select *\r\nfrom v$version\r\n";
InBlock.gif      tbxSql.Location 
= new Point(1010);
InBlock.gif      tbxSql.Size 
= new Size(240200);
InBlock.gif      tbxSql.Multiline 
= true;
InBlock.gif      tbxSql.ScrollBars 
= ScrollBars.Both;
InBlock.gif      tbxSql.AcceptsReturn 
= true;
InBlock.gif      tbxSql.WordWrap 
= true;
InBlock.gif      tbxSql.Anchor 
= (AnchorStyles.Top | AnchorStyles.Left);
InBlock.gif
InBlock.gif      tbxMsg 
= new TextBox();
InBlock.gif      tbxMsg.Location 
= new Point(10220);
InBlock.gif      tbxMsg.Size 
= new Size(240190);
InBlock.gif      tbxMsg.Multiline 
= true;
InBlock.gif      tbxMsg.ScrollBars 
= ScrollBars.Both;
InBlock.gif      tbxMsg.AcceptsReturn 
= true;
InBlock.gif      tbxMsg.WordWrap 
= true;
InBlock.gif      tbxMsg.Anchor 
= (AnchorStyles.Top | AnchorStyles.Bottom | AnchorStyles.Left);
InBlock.gif
InBlock.gif      dgOut 
= new DataGrid();
InBlock.gif      dgOut.Location 
= new Point(26010);
InBlock.gif      dgOut.Size 
= new Size(450436);
InBlock.gif      dgOut.CaptionVisible 
= false;
InBlock.gif      dgOut.ReadOnly 
= true;
InBlock.gif      dgOut.Anchor 
= (AnchorStyles.Top | AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Right);
InBlock.gif
ExpandedSubBlockStart.gifContractedSubBlock.gif      Controls.AddRange(
new Control[]dot.gif{btnSubmit, chkStru, lblTable, tbxSql, tbxMsg, tbxConn, dgOut});
InBlock.gif      Text 
= "数据库查询(ODPNET)";
InBlock.gif      ClientSize 
= new Size(720490);
InBlock.gif      WindowState 
= FormWindowState.Maximized;
InBlock.gif
InBlock.gif      ResumeLayout(
false);
ExpandedSubBlockEnd.gif    }

InBlock.gif    
InBlock.gif    
void DisplayError(Exception ex)
ExpandedSubBlockStart.gifContractedSubBlock.gif    
dot.gif{
InBlock.gif      StringBuilder sb 
= new StringBuilder();
InBlock.gif      
while (ex != null)
ExpandedSubBlockStart.gifContractedSubBlock.gif      
dot.gif{
InBlock.gif        sb.Append(
"");
InBlock.gif        sb.Append(ex.GetType());
InBlock.gif        sb.Append(Environment.NewLine);
InBlock.gif        OracleException e 
= ex as OracleException;
InBlock.gif        
if (e != null)
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif          
for (int i = 0; i < e.Errors.Count; i++) sb.AppendFormat(
InBlock.gif            
"Index: {1}{0}Message: {2}{0}DataSource: {3}{0}Source: {4}{0}Number: {5}{0}Procedure: {6}{0}", Environment.NewLine,
InBlock.gif            i, e.Errors[i].Message, e.Errors[i].DataSource, e.Errors[i].Source, e.Errors[i].Number, e.Errors[i].Procedure
InBlock.gif          );
ExpandedSubBlockEnd.gif        }

InBlock.gif        
else sb.Append(ex.Message);
InBlock.gif        sb.Append(Environment.NewLine);
InBlock.gif        ex 
= ex.InnerException;
ExpandedSubBlockEnd.gif      }

InBlock.gif      tbxMsg.Text 
= sb.ToString();
ExpandedSubBlockEnd.gif    }

InBlock.gif
InBlock.gif    
void Submit_Click(object sender, EventArgs e)
ExpandedSubBlockStart.gifContractedSubBlock.gif    
dot.gif{
InBlock.gif      btnSubmit.Enabled 
= false;
InBlock.gif      
string sql = tbxSql.Text.Trim();
InBlock.gif      
if (sql.Length == 0return;
InBlock.gif      
try
ExpandedSubBlockStart.gifContractedSubBlock.gif      
dot.gif{
InBlock.gif        
int rows = -2;
InBlock.gif        
string strType = "查询";
InBlock.gif        
using (OracleConnection conn = new OracleConnection(tbxConn.Text))
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif          conn.Open();
InBlock.gif          OracleCommand comm 
= new OracleCommand(sql, conn);
InBlock.gif          
if (!isQuery(sql))
ExpandedSubBlockStart.gifContractedSubBlock.gif          
dot.gif{
InBlock.gif            strType 
= "非查询";
InBlock.gif            rows 
= comm.ExecuteNonQuery();
ExpandedSubBlockEnd.gif          }

InBlock.gif          
else if (chkStru.Checked)
ExpandedSubBlockStart.gifContractedSubBlock.gif          
dot.gif{
InBlock.gif            strType 
= "表结构";
InBlock.gif            dgOut.DataSource 
= RunQueryTableStruct(comm);
ExpandedSubBlockEnd.gif          }

InBlock.gif          
else dgOut.DataSource = RunQueryTableData(comm);
ExpandedSubBlockEnd.gif        }

InBlock.gif        tbxMsg.Text 
= "运行 SQL 语句完毕(" + strType + ")";
InBlock.gif        
if (rows >= 0) tbxMsg.Text = "受影响的行数: " + rows.ToString("N0");
ExpandedSubBlockEnd.gif      }

InBlock.gif      
catch (Exception ex)
ExpandedSubBlockStart.gifContractedSubBlock.gif      
dot.gif{
InBlock.gif        DisplayError(ex);
ExpandedSubBlockEnd.gif      }

InBlock.gif      btnSubmit.Enabled 
= true;
ExpandedSubBlockEnd.gif    }

InBlock.gif    
InBlock.gif    
bool isQuery(string sql)
ExpandedSubBlockStart.gifContractedSubBlock.gif    
dot.gif{
InBlock.gif      
return sql.Substring(06).ToUpper() == "SELECT";
ExpandedSubBlockEnd.gif    }

InBlock.gif    
InBlock.gif    
private DataView RunQueryTableData(OracleCommand comm)
ExpandedSubBlockStart.gifContractedSubBlock.gif    
dot.gif{
InBlock.gif      OracleDataAdapter da 
= new OracleDataAdapter();
InBlock.gif      da.SelectCommand 
= comm;
InBlock.gif      DataSet ds 
= new DataSet();
InBlock.gif      da.Fill(ds);
InBlock.gif      
return ds.Tables[0].DefaultView;
ExpandedSubBlockEnd.gif    }

InBlock.gif
InBlock.gif    
private DataView RunQueryTableStruct(OracleCommand comm)
ExpandedSubBlockStart.gifContractedSubBlock.gif    
dot.gif{
InBlock.gif      DataTable dt 
= new DataTable();
InBlock.gif      dt.Columns.Add(
"#"typeof(int));
InBlock.gif      dt.Columns.Add(
"字段名"typeof(string));
InBlock.gif      dt.Columns.Add(
"数据类型"typeof(string));
InBlock.gif      dt.Columns.Add(
"源数据类型"typeof(string));
InBlock.gif      dt.Columns.Add(
"大小"typeof(string));
InBlock.gif      dt.Columns.Add(
"备注"typeof(string));
InBlock.gif      
using (OracleDataReader r = comm.ExecuteReader(CommandBehavior.KeyInfo))
ExpandedSubBlockStart.gifContractedSubBlock.gif      
dot.gif{
InBlock.gif        DataTable dt0 
= r.GetSchemaTable();
InBlock.gif        
//return dt0.DefaultView;
InBlock.gif
        foreach (DataRow dr0 in dt0.Rows)
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif          DataRow dr 
= dt.NewRow();
InBlock.gif          dr[
0= (int)dr0["ColumnOrdinal"];
InBlock.gif          dr[
1= (string)dr0["ColumnName"];
InBlock.gif          dr[
2= GetBriefType(dr0["DataType"]);
InBlock.gif          dr[
3= ((OracleDbType)dr0["ProviderType"]).ToString();
InBlock.gif          dr[
4= string.Format(
InBlock.gif            
"({0},{1}) {2}", GetInt16(dr0["NumericPrecision"]), GetInt16(dr0["NumericScale"]), (int)dr0["ColumnSize"]
InBlock.gif            );
InBlock.gif          dr[
5= string.Format(
InBlock.gif            
"{0}{1}{2}{3}{4}{5}{6}{7}{8}{9}",
InBlock.gif            isTrue(dr0[
"AllowDBNull"   ]) ? "AllowDBNull "  : "",
InBlock.gif            isTrue(dr0[
"IsKey"         ]) ? "Key "          : "",
InBlock.gif            isTrue(dr0[
"IsUnique"      ]) ? "Unique "       : "",
InBlock.gif            isTrue(dr0[
"IsLong"        ]) ? "Long "         : "",
InBlock.gif            isTrue(dr0[
"IsReadOnly"    ]) ? "ReadOnly "     : "",
InBlock.gif            isTrue(dr0[
"IsRowID"       ]) ? "RowID "        : "",
InBlock.gif            isTrue(dr0[
"IsAliased"     ]) ? "Aliased "      : "",
InBlock.gif            isTrue(dr0[
"IsByteSemantic"]) ? "ByteSemantic " : "",
InBlock.gif            isTrue(dr0[
"IsExpression"  ]) ? "Expression "   : "",
InBlock.gif            isTrue(dr0[
"IsHidden"      ]) ? "Hidden"        : ""
InBlock.gif            );
InBlock.gif          dt.Rows.Add(dr);
ExpandedSubBlockEnd.gif        }

ExpandedSubBlockEnd.gif      }

InBlock.gif      
return dt.DefaultView;
ExpandedSubBlockEnd.gif    }

InBlock.gif    
InBlock.gif    
bool isTrue(object obj)
ExpandedSubBlockStart.gifContractedSubBlock.gif    
dot.gif{
InBlock.gif      
if (obj == DBNull.Value) return false;
InBlock.gif      
return (bool)obj;
ExpandedSubBlockEnd.gif    }

InBlock.gif    
InBlock.gif    
short GetInt16(object obj)
ExpandedSubBlockStart.gifContractedSubBlock.gif    
dot.gif{
InBlock.gif      
if (obj == DBNull.Value) return -1;
InBlock.gif      
else return (short)obj;
ExpandedSubBlockEnd.gif    }

InBlock.gif    
InBlock.gif    
string GetBriefType(object obj)
ExpandedSubBlockStart.gifContractedSubBlock.gif    
dot.gif{
InBlock.gif      
string s = (obj as Type).ToString();
InBlock.gif      
if (string.CompareOrdinal(s, 0"System."07== 0) s = s.Substring(7);
InBlock.gif      
return s;
ExpandedSubBlockEnd.gif    }

InBlock.gif
InBlock.gif    
static void Main()
ExpandedSubBlockStart.gifContractedSubBlock.gif    
dot.gif{
InBlock.gif      Application.Run(
new OdpnetDlg());
ExpandedSubBlockEnd.gif    }

ExpandedSubBlockEnd.gif  }

ExpandedBlockEnd.gif}

None.gif

  此外,该程序还有以下各种版本:
System.Data.OracleClient;
System.Data.SqlClient;
System.Data.OleDb;
System.Data.Odbc;
  限于篇幅,这里不就贴出源程序了,各位可以自己在ODP.NET版本的基础上稍做修改就行了。
  同样是Oracle数据库,使用Oracle.DataAccess.Client和System.Data.OracleClient还是有区别的,请参阅:
Comparing the Microsoft .NET Framework 1.1 Data Provider for Oracle and the Oracle Data Provider for .NET
  例如,对于数据库中的NUMBER类型,Oracle.DataAccess.Client对应的.NET类型可以是byte、short、int、long、decimal等类型,而System.Data.OracleClient一般都对应为decimal类型。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值