Maison > Article > base de données > C#连接oracle实现增删改查
以users表为例,有三个字段,自增长的编号id,int类型;名称name,nvarchar类型,密码pwd,nvarchar类型 首先在vs2005中引入System.Data.OracleClient;命名空间 publicint Insert(stringname, string pwd) { OracleConnectionconn = new OracleConnection(@D
以users表为例,有三个字段,自增长的编号id,int类型;名称name,nvarchar类型,密码pwd,nvarchar类型
首先在vs2005中引入System.Data.OracleClient;命名空间
publicint Insert(stringname, string pwd)
{
OracleConnectionconn = new OracleConnection(@"Data Source=SBZX;User ID=simis;Password=zeda");
conn.Open();
stringsql = "insert into users(name,pwd)values(:name,:pwd)";
OracleCommandcmd = new OracleCommand(sql,conn);
OracleParameter parn = new OracleParameter(":name", name);
cmd.Parameters.Add(parn);
OracleParameter parp = new OracleParameter(":pwd", name);
cmd.Parameters.Add(parp);
int result = cmd.ExecuteNonQuery(); //result接收受影响行数,也就是说result大于0的话表示添加成功
conn.Close();
cmd.Dispose();
return result;
}
publicint Update(int id)
{
OracleConnectionconn = new OracleConnection(@"Data Source=SBZX;User ID=simis;Password=zeda");
conn.Open();
stringsql = "delete from users where id=:id";
OracleCommandcmd = new OracleCommand(sql,conn);
OracleParameterpari = new OracleParameter(":id", id);
cmd.Parameters.Add(pari);
int result = cmd.ExecuteNonQuery(); //result接收受影响行数,也就是说result大于0的话表示添加成功
conn.Close();
cmd.Dispose();
return result;
}
publicint Insert(stringname, string pwd, intid)
{
OracleConnectionconn = new OracleConnection(@"Data Source=SBZX;User ID=simis;Password=zeda");
conn.Open();
stringsql = "update users set name=:name,pwd=:pwdwhere id=:id";
OracleCommandcmd = new OracleCommand(sql,conn);
OracleParameterparn = new OracleParameter(":name", name);
cmd.Parameters.Add(parn);
OracleParameterparp = new OracleParameter(":pwd", name);
cmd.Parameters.Add(parp);
OracleParameterpari = new OracleParameter(":id", id);
cmd.Parameters.Add(pari);
intresult = cmd.ExecuteNonQuery();
conn.Close();
cmd.Dispose();
returnresult;
}
publicDataTable Select()
{
OracleConnectionconn = new OracleConnection(@"Data Source=SBZX;User ID=simis;Password=zeda");
conn.Open();
stringsql = "select * from users";
OracleCommandcmd = new OracleCommand(sql,conn);
OracleDataAdapteroda = new OracleDataAdapter(cmd);
DataTable dt = new DataTable();
oda.Fill(dt);
conn.Close();
cmd.Dispose();
return dt;
}
方法写好后,下面举一个查询的例子,在form窗体中拖一个DataGridView,然后在Load方法中
private void Form1_Load(object sender, EventArgs e)
{
dataGridView1.DataSource = Select();
}
这样一运行,DataGridView中就会显示数据了