- VS2012中新建Windows窗体应用程序。Oracle中建测试数据表Test。(此处需要环境已配好情况下进行操作)
用到的数据表
向Windows窗体应用程序,设计界面托一个按钮和一个数据表格视图控件(需要指明数据源,只需添加一次,下次使用同一数据源时不需再添加)
在拖DataGridView控件时弹出选项——添加数据源-----数据库-------数据集-----新建连接----输入数据库账户密码-----确定
- 添加Oracle.DataAccess.dll引用(项目中添加System.Data.OracleClient的引用,
然后程序中(Form.cs文件中)添加using System.Data.OracleClient;),然后在按钮事件下写入如下代码
//关键代码
string connectionString;
string queryString;
// 连接字符串1
connectionString = "Data Source=127.0.0.1/orcl;User ID=test;PassWord=test";
//查询语句
queryString = "SELECT * FROM TEST";
OracleConnection myConnection = new OracleConnection(connectionString);
OracleCommand myORACCommand = myConnection.CreateCommand();
myORACCommand.CommandText = queryString;
myConnection.Open();
OracleDataAdapter oraDA = new OracleDataAdapter(myORACCommand);
DataSet ds = new DataSet();
oraDA.Fill(ds);
myConnection.Close();
DataTable dtbl = ds.Tables[0];
this.dataGridView1.DataSource = dtbl;
完整版代码
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.OracleClient;
namespace WindowsFormsApplication4
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e) //按钮事件
{
string connectionString;
string queryString;
// 连接字符串
connectionString = "Data Source=127.0.0.1/orcl;User ID=test;PassWord=test";
//查询语句
queryString = "SELECT * FROM TEST";
OracleConnection myConnection = new OracleConnection(connectionString);
OracleCommand myORACCommand = myConnection.CreateCommand();
myORACCommand.CommandText = queryString;
myConnection.Open();
OracleDataAdapter oraDA = new OracleDataAdapter(myORACCommand);
DataSet ds = new DataSet();
oraDA.Fill(ds);
myConnection.Close();
DataTable dtbl = ds.Tables[0];
this.dataGridView1.DataSource = dtbl;
}
}
}
查询效果
一起学习,一起进步。