目录
一、引入参考
1. ConfigurationManager的调用前提:
2. NpgsqlConnection的调用前提:
3. OracleConnection的调用前提:
二、设置数据库链接字串
1. 在App.config中设定链接数据库详情
2. 获取数据库链接字串
三、调用
1.调用Oracle数据库
2.调用postgre数据库
3.结合不同数据库联合查询
一、引入参考
1. ConfigurationManager的调用前提:
方案总管 > 项目的“参考”> 右键-加入参考 > 在架构中勾选System.Configuration > 确定。
代码需引用:using System.Configuration;
2. NpgsqlConnection的调用前提:
点击工具栏的“工具” > NuGet套件管理员 > 管理方案的NuGet套件(程式若启动了,先终止运行) > 搜寻插件名Npgsql > 查看该项目是否安装。
代码需引用:using Npgsql;
3. OracleConnection的调用前提:
点击工具栏的“工具” > NuGet套件管理员 > 管理方案的NuGet套件(程式若启动了,先终止运行) > 搜寻插件名Oracle.ManagedDataAccess > 查看该项目是否安装。
代码需引用:using Oracle.ManagedDataAccess.Client;
二、设置数据库链接字串
1. 在App.config中设定链接数据库详情
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.7.2" />
</startup>
<appSettings>
<add key="BookOracle" value="User Id=Luobogan;Password=12345678;Data Source=(DESCRIPTION=(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST=10.XXX.XXX.XXX)(PORT=1521)))(CONNECT_DATA=(SERVICE_NAME=Book)))"/>
<add key="BookPostgre" value="Host=10.XXX.XXX.XXX;Port=5432;Database=Book;Username=Luobogan;Password=12345678;"/>
</appSettings>
</configuration>
2. 获取数据库链接字串
// 获取Oracle链接字串时:
private string OracleConn = ConfigurationManager.AppSettings["BookOracle"].ToString();
// 获取postgre链接字串时:
private string PgConn = ConfigurationManager.AppSettings["BookPostgre"].ToString();
三、调用
1.调用Oracle数据库
// 引入组件
using System.Configuration;
using System.Data;
using Oracle.ManagedDataAccess.Client;
// 获取数据库信息&设置查询语句(读取设定)
private string OracleConn = ConfigurationManager.AppSettings["BookOracle"].ToString();
string bookpublishplace = "新闻出版社";
string OracleSql = $@"SELECT * FROM ""Book"" WHERE publishplace='{bookpublishplace}' ";
// 查询Oracle数据库
DataTable GetResTb = OracleQuery(OracleSql, OracleConn);
List GetResList = GetResTb.AsEnumerable().Where(x => x.Field<string>("author") == "萝卜").Select(x => x.Field<string>("bookname")).Distinct().ToList();
public DataTable OracleQuery(string sql, string connstr)
{
try
{
using (OracleConnection conn = new OracleConnection(connstr))
{
conn.Open();
OracleCommand cmd = new OracleCommand(sql, conn);
// 执行查询,以table形式返回查询结果
OracleDataAdapter dataAdapter = new OracleDataAdapter(cmd);
DataTable dt = new DataTable();
dataAdapter.Fill(dt);
conn.Close();
return dt;
// 执行新增/更新/删除,用数字0,1返回更新结果
// int result = cmd.ExecuteNonQuery();
// conn.Close();
// return result;
}
}
catch (Exception ex)
{
// 执行查询,以空值null返回异常值
return null;
// 执行新增/更新/删除,用数字-1返回异常值
// return -1;
}
}
// 执行Oracle数据库的存储过程
OracleParameter[] OracleParameters = new OracleParameter[] {
new OracleParameter("存储过程栏位名1", OracleDbType.NVarchar2, 20, Factoryname, ParameterDirection.Input),
new OracleParameter("存储过程栏位名2", OracleDbType.NVarchar2, 20, Factoryname, ParameterDirection.Input),
new OracleParameter("返回存储过程Table1", OracleDbType.RefCursor, 40, "", ParameterDirection.Output),
new OracleParameter("返回存储过程Table2", OracleDbType.RefCursor, 40, "", ParameterDirection.Output),
new OracleParameter("return_sql", OracleDbType.NVarchar2, 20000, "", ParameterDirection.Output),
new OracleParameter("return_code", OracleDbType.Int32, 6, 0, ParameterDirection.Output),
};
DataSet BookDataSet = OracleQueryProcedure(OracleConn, "执行过程名", OracleParameters);
authorname = '萝卜'
DataTable getResTb = BookDataSet.Tables[0];
DataRow[] rows = getResTb.Select($"author ='{authorname}'");
if (rows.Length > 0)
{
getColumnRes = rows[0]["authorage"].ToString()
}
public DataSet OracleQueryProcedure(string connstr, string procedurename, OracleParameter[] Parameter)
{
try
{
using (OracleConnection conn = new OracleConnection(connstr))
{
conn.Open();
OracleCommand cmd = new OracleCommand();
cmd.CommandText = procedurename;
cmd.Connection = conn;
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddRange(Parameter);
cmd.ExecuteNonQuery();
OracleDataAdapter dataAdapter = new OracleDataAdapter(cmd);
DataSet ds = new DataSet();
dataAdapter.Fill(ds);
conn.Close();
return ds;
}
}
catch (Exception ex)
{
return null;
}
}
// 批量插入Oracle数据库
private string targetConn = ConfigurationManager.AppSettings["OracleDB"].ToString();
DataTable resData = 获取的表数据;
Dictionary<string, string> AddColumnMappings = new Dictionary<string, string>() {
{ "待插入datatable的栏位名", "数据库表的栏位名" },
{ "book_id", "BOOKID" },
{ "book_name", "BOOKNAME" },
};
var res = OracleBulkInsert(targetConn, "表名", resData, AddColumnMappings) == 1 ? "success" : "fail";
Console.WriteLine($"res:{res}");
/// <summary>
/// Oracle数据库--批量插入
/// </summary>
/// <param name="connstr">数据库链接</param>
/// <param name="targettb">目标表</param>
/// <param name="dataTable">待插入数据</param>
/// <param name="AddColumnMappings">列名映射</param>
/// <returns>int</returns>
public int OracleBulkInsert(string connstr, string targettb, DataTable dataTable, Dictionary<string, string> AddColumnMappings)
{
try
{
using (OracleConnection conn = new OracleConnection(connstr))
{
conn.Open();
using (var bulkCopy = new OracleBulkCopy(conn)) // 使用 OracleBulkCopy 来批量插入数据
{
bulkCopy.DestinationTableName = targettb; // 设置Oracle目标表名
bulkCopy.BatchSize = 1000; // 每次批量插入1000行数据
foreach (var kvp in AddColumnMappings)
{
bulkCopy.ColumnMappings.Add(kvp.Key, kvp.Value); // DataTable 的列名会映射到 Oracle 表的列名
}
bulkCopy.WriteToServer(dataTable); // 执行批量插入
}
return 1;
}
}
catch (Exception ex)
{
//throw ex;
return -1;
}
}
2.调用postgre数据库
在另一篇文章中:Backend - ADO.NET(C# 操作PostgreSQL DB)_c# postgresql-CSDN博客
3.结合不同数据库联合查询
以下写法是结合了ADO.NET 和 LINQ to Objects。
class CombineTb
{
public string newbookname { get; set; } // 结合新表的栏位1
public string newbookauthor { get; set; } // 结合新表的栏位2
public string newbookplace { get; set; } // 结合新表的栏位3
}
string OracleSql = $@"SELECT * FROM Book' ";
string PgSql = $@"SELECT bookplace,author,bookname FROM BookPublish";
DataTable GetOracleResTb = OracleQuery(OracleSql, OracleConn);
DataTable GetPostgreResTb = PgQuery(PgSql, PgConn);
List<CombineTb> CombineData = (from a in GetOracleResTb.AsEnumerable()
join b in GetPostgreResTb.AsEnumerable()
on new { bookname = a.Field<string>("name"), author = a.Field<string>("author") } equals
new { bookname = b.Field<string>("bookname"), author = b.Field<string>("authorname") }
select new CombineTb
{
newbookname = b.Field<string>("bookname"),
newbookauthor = b.Field<string>("authorname"),
newbookplace = b.Field<string>("bookplace")
}).Distinct().ToList();
List<string> authorList = CombineData.Where(x => x.newbookname == "数据结构").Select(x => x.newbookauthor).Distinct().ToList();