How to use a Oracle database in ASP.NET without Entity Framework? - sql

Can someone tell me in a simple way, how can I use an Oracle DB in my ASP.NET MVC 5 project? I have tried different articles but I didn't get a clear answer...

I think this is the simple way to do this:
using System.Data.OracleClient;
public string GetConnectionString()
{
String connString = "SERVER=(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=YourHostName)(PORT=YourPort))(CONNECT_DATA=(SERVICE_NAME=YourServiceName)));uid=YourUserId;pwd=YourPassword;";
return connString;
}
public void ConnectingToOracle()
{
string connectionString = GetConnectionString();
using (OracleConnection connection = new OracleConnection())
{
connection.ConnectionString = connectionString;
connection.Open();
OracleCommand command = connection.CreateCommand();
string sql = "select * from MyDatabase where name like '%John Paul%'";
command.CommandText = sql;
OracleDataReader reader = command.ExecuteReader();
while (reader.Read())
{
string myField = (string)reader["address"]; //Get the address of John Paul
}
}
}

Related

Is there a way to pass parameter into XPath NpgsqlCommand?

In SQL Server I can use sql:variable:
string sql = "select * from mytable where xml_column.exist('//Tag[text()=sql:variable(\"#value\")]') = 1";
I was trying to find similar way to pass parameter into NpgsqlCommand. This one for example does not fail but also does not return any data:
string sql = "select * from mytable where xmlexists('//Tag[text()=\"#value\"]' PASSING BY REF xml_column) = true";
Is there any way of doing it?
Thanks!
Here is a code snippet:
string connstr = "PORT=5432;DATABASE=mydb;HOST=myhost;USER ID=myuser;PASSWORD=mypassword";
using (NpgsqlConnection connection = new NpgsqlConnection(connstr))
{
connection.Open();
string sql = "select xml_column from mytable where xmlexists('//Tag[text()=\"#value\"]' PASSING BY REF xml_column) = true";
using (var cmd = connection.CreateCommand())
{
cmd.CommandText = sql;
cmd.Parameters.AddWithValue("#value", "my value");
using (var reader = cmd.ExecuteReader())
{
while (reader.Read())
{
reader[0].Dump();
}
}
}
connection.Close();
}
Cross-posted on github, see answer there: https://github.com/npgsql/npgsql/issues/2946

MVC 5 Convert SQL Query to EF Linq

I have this result:
The problem is that I am not using the power of EF.
I followed this EF tutorial but i'm now able to do it.
ActivityLogController.cs
using System;
...
namespace AccountSystem.Controllers
{
public class ActivityLogController : Controller
{
private ApplicationDbContext db = new ApplicationDbContext();
// GET: ActivityLog
public ActionResult Index()
{
/* var id = User.Identity.GetUserId();
var Emaill = (from x in db.Users
where x.Id == id
select x.Email).Single(); */
//string Access = AccessQ.ToString();
IEnumerable<ActivityLogViewData> model = null;
List<ActivityLogViewData> verify = new List<ActivityLogViewData>();
SqlConnection connection = new SqlConnection("xxx");
connection.Open();
SqlCommand command = new SqlCommand("", connection);
command.CommandText = "select dbo.AspNetUsers.Email,dbo.AspNetUsers.UserName,dbo.ActivityLogModels.ID,dbo.ActivityLogModels.Acess,dbo.AspNetUsers.Id from dbo.ActivityLogModels inner join dbo.AspNetUsers on dbo.ActivityLogModels.userID=dbo.AspNetUsers.Id";
SqlDataReader dr = command.ExecuteReader();
while (dr.Read())
{
verify.Add(new ActivityLogViewData { Email = dr[0].ToString(), UserName = dr[1].ToString(), accessID = Convert.ToInt32(dr[2].ToString()), Acess = Convert.ToDateTime(dr[3].ToString()), userID = dr[4].ToString()});
}
connection.Close();
//verify.Add(new ActivityLogViewData {Email = Emaill });
//return View(db.ActivityLog.ToList());
return View(verify);
}
The commented lines are my unsuccessful tries.
Can someone convert this to use EF?
TiA!

ASP.NET 5 - DataSet, DataTable and friends

I'm creating a new webservice in ASP.NET 5 using the new .NET Core library, so far I've only hit an issue with using DataSet and DataTable.
According to this site they are not included at this moment in time, which is fine, but I don't know what alternatives I have at this time, so I'm just looking for some guidance.
I have the following code:
public string Get(string p_sUserId, string p_sUserPassword, int p_iCustId)
{
Select qrySelect = new Select();
using (SqlConnection conn = new SqlConnection(Startup.ConnectionString))
{
using (SqlCommand cmd = new SqlCommand(qrySelect.getData(), conn))
{
cmd.Parameters.AddWithValue("#Id", sTestId);
using (SqlDataAdapter da = new SqlDataAdapter(cmd))
{
using (DataSet ds = new DataSet())
{
// foo
// bar
}
}
}
}
return "value";
}
How should I handle the data that is being return from the query? I need to build and return a string using the above data fetched from the query. Any help and guidance would be appreciated.
I believe SqlDataReader should work.
string sql = "SELECT * FROM Table";
using (SqlConnection con = new SqlConnection(Startup.ConnectionString)) {
con.Open();
using (SqlCommand command = new SqlCommand(sql, con)) {
using (IDataReader dr = command.ExecuteReader()) {
while (dr.Read()) {
//process data
}
}
}
}
DataTable and SqlDBAdapter are now supported using .NET Standard 2.0. Upgrade to VS2017 Preview, add System.Data.Common and System.Data.SqlClient nugets, and the code below should work. More detail at the blog post here -> https://blogs.msdn.microsoft.com/devfish/2017/05/15/exploring-datatable-and-sqldbadapter-in-asp-net-core-2-0/ . GitHub repo here -> https://github.com/jhealy/aspdotnetcore/tree/master/SqlClientPlay20 .
public static DataTable ExecuteDataTableSqlDA(SqlConnection conn, CommandType cmdType, string cmdText, SqlParameter[] cmdParms)
{
System.Data.DataTable dt = new DataTable();
System.Data.SqlClient.SqlDataAdapter da = new SqlDataAdapter(cmdText, conn);
da.Fill(dt);
return dt;
}

Cannot insert numeric value into my SQL table

I currently have 2 tables in my database, 1 with an autonumeric value called ZoekcriteriaID which is the primary key off the table Zoekcriteria.
I want to add the primary key (ZoekcriteriaID) to my other table called Resultaten as a forgeign key but I keep getting the same error.
It seems like cmd1.Parameters.AddWithValue("#ZoekcriteriaID",Convert.ToInt32(sqlZoekcriteriaID)); keeps trying to add the entire query as a numeric value and I can't seem to figure out why.
Could anyone help me?
namespace Proftaak
{
class Mysearch
{
public string zoekterm = "";
int resultaat = 1;
public string Zoekterm
{
get
{
return zoekterm;
}
set
{
zoekterm = value;
}
}
public void InsertZoekcriteria()
{
OleDbConnection connection = new OleDbConnection();
connection.ConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\martijn\Dropbox\Proftaak Periode 2 Identity\Database11.accdb;
Persist Security Info=False;";
connection.Open();
string sqlstring = "INSERT INTO Zoekcriteria (ZoekCriteria) values ('" + Zoekterm + "')";
OleDbCommand cmd = new OleDbCommand(sqlstring, connection);
cmd.ExecuteNonQuery();
connection.Close();
}
public void searchding()
{
const string apiKey = "AIzaSyDIm9ZOWD8Zd-2tHy5r3c0R-_XjdEFaXGE";
const string searchEngineId = "003470263288780838160:ty47piyybua";
string query = zoekterm;
CustomsearchService customSearchService = new CustomsearchService(new Google.Apis.Services.BaseClientService.Initializer() { ApiKey = apiKey });
Google.Apis.Customsearch.v1.CseResource.ListRequest listRequest = customSearchService.Cse.List(query);
listRequest.Cx = searchEngineId;
Search search = listRequest.Execute();
OleDbConnection connection = new OleDbConnection();
connection.ConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\martijn\Dropbox\Proftaak Periode 2 Identity\Database11.accdb;
Persist Security Info=False;";
connection.Open();
string sqlZoekcriteriaID = "SELECT ZoekcriteriaID from Zoekcriteria where Zoekcriteria='" + query + "'";
OleDbCommand cmdZoekcriteria = new OleDbCommand(sqlZoekcriteriaID, connection);
cmdZoekcriteria.ExecuteNonQuery();
foreach (var item in search.Items)
{
string sqlstring1 = #"INSERT INTO Resultaat (ResultatenID,ZoekcriteriaID, Titel, Webadress) VALUES (#ResultatenID,#ZoekcriteriaID, #Titel, #Webadress)";
OleDbCommand cmd1 = new OleDbCommand(sqlstring1, connection);
cmd1.Parameters.AddWithValue("#ResultatenID", resultaat);
cmd1.Parameters.AddWithValue("#ZoekcriteriaID",Convert.ToInt32(sqlZoekcriteriaID));
cmd1.Parameters.AddWithValue("#Titel", item.Title);
cmd1.Parameters.AddWithValue("#Webadress", item.Link);
// string sqlstring2= "INSERT INTO Resultaat(Titel) values ('"+item.Title+"')";
// OleDbCommand cmd2 = new OleDbCommand(sqlstring2, connection);
resultaat++;
cmd1.ExecuteNonQuery();
}
connection.Close();
That's because it does:
string sqlZoekcriteriaID = "SELECT ZoekcriteriaID from Zoekcriteria where Zoekcriteria='" + query + "'";
cmd1.Parameters.AddWithValue("#ZoekcriteriaID",Convert.ToInt32(sqlZoekcriteriaID));
What you want is use the result of the query. What you should do is described in the answer to this question.
You should also rethink the naming of your variables; queryis not a query, for example, just a search condition.
Before close the connection, recover the identity number, like this:
OleDbCommand cmd = new OleDbCommand(sqlstring, connection);
cmd.ExecuteNonQuery();
cmd.CommandText = "SELECT ##IDENTITY";
integer ZoekcriteriaID = cmd.ExecuteScalar()
connection.Close();
Than you can use the ZoekcriteriaID on the other insert.
Refer to this link

Retrieve SQL Statement Does Not Go Into While Loop

I am having problem when doing retrieve function in 3-tier in C#. Here is the codes:
public DistributionStandardPackingUnits getSPUDetail(string distributionID)
{
DistributionStandardPackingUnits SPUFound = new DistributionStandardPackingUnits();
using (var connection = new SqlConnection(FoodBankDB.connectionString))
{
SqlCommand command = new SqlCommand("SELECT name, description, quantity FROM dbo.DistributionStandardPackingUnits WHERE distribution = '" + distributionID + "'", connection);
connection.Open();
using (var dr = command.ExecuteReader())
{
while (dr.Read())
{
string name = dr["name"].ToString();
string description = dr["description"].ToString();
string quantity = dr["quantity"].ToString();
SPUFound = new DistributionStandardPackingUnits(name, description, quantity);
}
}
}
return SPUFound;
}
When I run in browser, it just won't show up any retrieved data. When I run in debugging mode, I realized that when it hits the while loop, instead of executing the dr.Read(), it simply just skip the entire while loop and return null values. I wonder what problem has caused this. I tested my query using the test query, it returns me something that I wanted so I think the problem does not lies at the Sql statement.
Thanks in advance.
Edited Portion
public static SqlDataReader executeReader(string query)
{
SqlDataReader result = null;
System.Diagnostics.Debug.WriteLine("FoodBankDB executeReader: " + query);
SqlConnection connection = new SqlConnection(connectionString);
SqlCommand command = new SqlCommand(query, connection);
connection.Open();
result = command.ExecuteReader();
connection.Close();
return result;
}