使用ManagedDataAccess.dll构建增删改查语句
时间: 2024-01-15 12:47:01 浏览: 63
使用ManagedDataAccess.dll可以很方便地构建增删改查语句,以下是一些示例代码:
1. 插入数据:
```csharp
string connectionString = "Data Source=myServerAddress;Initial Catalog=myDataBase;User ID=myUsername;Password=myPassword;";
string insertQuery = "INSERT INTO myTable (column1, column2, column3) VALUES (@val1, @val2, @val3)";
using (OracleConnection connection = new OracleConnection(connectionString))
{
using (OracleCommand command = new OracleCommand(insertQuery, connection))
{
command.Parameters.Add("@val1", OracleDbType.Varchar2).Value = "value1";
command.Parameters.Add("@val2", OracleDbType.Varchar2).Value = "value2";
command.Parameters.Add("@val3", OracleDbType.Varchar2).Value = "value3";
connection.Open();
command.ExecuteNonQuery();
}
}
```
2. 更新数据:
```csharp
string connectionString = "Data Source=myServerAddress;Initial Catalog=myDataBase;User ID=myUsername;Password=myPassword;";
string updateQuery = "UPDATE myTable SET column1 = @val1 WHERE column2 = @val2";
using (OracleConnection connection = new OracleConnection(connectionString))
{
using (OracleCommand command = new OracleCommand(updateQuery, connection))
{
command.Parameters.Add("@val1", OracleDbType.Varchar2).Value = "new_value";
command.Parameters.Add("@val2", OracleDbType.Varchar2).Value = "old_value";
connection.Open();
command.ExecuteNonQuery();
}
}
```
3. 删除数据:
```csharp
string connectionString = "Data Source=myServerAddress;Initial Catalog=myDataBase;User ID=myUsername;Password=myPassword;";
string deleteQuery = "DELETE FROM myTable WHERE column1 = @val1";
using (OracleConnection connection = new OracleConnection(connectionString))
{
using (OracleCommand command = new OracleCommand(deleteQuery, connection))
{
command.Parameters.Add("@val1", OracleDbType.Varchar2).Value = "value_to_delete";
connection.Open();
command.ExecuteNonQuery();
}
}
```
4. 查询数据:
```csharp
string connectionString = "Data Source=myServerAddress;Initial Catalog=myDataBase;User ID=myUsername;Password=myPassword;";
string selectQuery = "SELECT * FROM myTable WHERE column1 = @val1";
using (OracleConnection connection = new OracleConnection(connectionString))
{
using (OracleCommand command = new OracleCommand(selectQuery, connection))
{
command.Parameters.Add("@val1", OracleDbType.Varchar2).Value = "value_to_select";
connection.Open();
using (OracleDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
// do something with the data
}
}
}
}
```
注意:以上示例代码中的 OracleDbType.Varchar2 是 Oracle 数据库中的一种数据类型,如果你使用的是其他数据库,需要根据该数据库的数据类型来修改。另外,示例代码中的 SQL 语句都是简单的语句,如果你需要构建更复杂的 SQL 语句,需要使用更高级的技巧,比如使用存储过程、使用动态 SQL 等。
阅读全文