trying to connect web API's to oracle db - c#

trying to connect web API to oracle DB.
I have successfully connected with SQL server but I have no idea about oracle DB.what I have done is=> created a controller and write a get and post API method in it. and on the web.config I have added connectionStrings. I am attaching my SQL connection code.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using System.Data.SqlClient;
using System.Data;
using System.Configuration;
namespace API2.Controllers
{
public class IndexController : ApiController
{
[HttpGet]
[Route("getUsers")]
public HttpResponseMessage Get_Users()
{
DataTable dt = new DataTable();
string str_Msg = string.Empty;
string Query = string.Empty;
string consString = ConfigurationManager.ConnectionStrings["xyz"].ConnectionString;
Query = "SELECT * from xyz";
using (SqlConnection con = new SqlConnection(consString))
{
using (SqlCommand _SqlCommand = new SqlCommand(Query, con))
{
_SqlCommand.CommandType = CommandType.Text;
using (SqlDataAdapter _adapater = new SqlDataAdapter(_SqlCommand))
{
_adapater.Fill(dt);
}
Query = string.Empty;
}
}
return Request.CreateResponse(HttpStatusCode.OK, dt, Configuration.Formatters.JsonFormatter);
}
}
<connectionStrings>
<add name="xyz" connectionString="Data Source= xyz; Integrated Security=false;Initial Catalog= xyz; uid=xyz; Password=xyz;" providerName="System.Data.SqlClient" />
</connectionStrings>
I have no idea how to do the same connectivity with oracle DB. please help me with this.
thank you so much.

Referring to this
Your connection string will look like
Data Source=MyOracleDB;User Id=myUsername;Password=myPassword;Integrated Security=no;

Related

System.Data.SqlClient.SqlException in Entity Framework (Web API)

My web controller code:
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using System.Web.Http.Description;
using Account;
namespace Account.Controllers
{
public class ORDER_DETAILController : ApiController
{
private restaurantEntities db = new restaurantEntities();
[HttpGet]
[Route("api/ORDER_DETAIL/PendingOrders/{id}")]
[ResponseType(typeof(ORDER_DETAIL))]
public IQueryable<Orders> PendingOrders(int id)
{
Class1 obj = new Class1();
return obj.GetOrders(id);
}
}
}
Class:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using Dapper;
namespace AccountStoredProc.Controllers
{
public class Class1
{
public IQueryable<Orders> GetOrders(int id)
{
using(SqlConnection conn = new SqlConnection("integrated security = true ; data source = RAHUL - PAVILION;"))
{
conn.open();
return conn.Query<Orders>($"select * from ORDER_DETAIL WHERE VEN_ID={id} and ORD_STATUS='PENDING' ").AsQueryable();
}
}
}
}
When I hit the below URL:
https://localhost:44331/api/ORDER_DETAIL/PendingOrders/1
I get this error:
A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: Named Pipes Provider, error: 40 - Could not open a connection to SQL Server)
System.Data.SqlClient.SqlException
I know I already opened the connection while creating EF but how can I execute my query in GetOrders() without a SqlConnection variable called conn I am not able to execute my query without conn variable?
NOTE: connection establishment is working in normal console application and other predefined methods like get, search in account controller but in my predefined method it is not working.
Please check your connection string, especially on spaces
example format for connectiong string:
`connetionString = #"Data Source=WIN-50GP30FGO75; integrated security = true; Initial Catalog=Demodb;User ID=sa;Password=demol23";`

I would like to display data from a database in an MVC project using sql adapter

I am looking to use the SQL Data adapter feature inside of MVC to display the results from a query string inside of my project. I'm new to using the sql adapter feature but I would like to get used to it. Simply put, I need to know what to put in my controller, and if i need to create a model, and what to put in my view.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
namespace NewHoyaIntranet.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
DataSet data;
DataTable table;
using (SqlConnection connection = new
SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["HUT"]
.ConnectionString))
{
connection.Open();
SqlCommand select = new SqlCommand("SELECT * FROM HUT.dbo.XREF_HIOI_LensStyle_HTL", connection);
SqlDataAdapter adapter = new SqlDataAdapter();
adapter.SelectCommand = select;
data = new DataSet();
adapter.Fill(data, "HUT.dbo.XREF_HIOI_LensStyle_HTL");
table = data.Tables[0]; //is the [0] really correct?
}
return View(/* Right now nothing is returning in any view/ how do i tie the view in? */);
}
}
}

Is this the correct way for connecting database (.mdf file) to visual studio project?

for this i am not getting any output thought there is not any error or warning... i guess the problem is with connection string but not sure, is it?? i have created a database name RV(.mdf file) in SQL server data tool and connected it to this project in visual studio.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data;
using System.Data.Common;
using System.Data.SqlClient;
using System.Configuration;
namespace student_TableConnectTry1
{
class Program
{
static void Main(string[] args)
{
using (SqlConnection cn = new SqlConnection())
{
cn.ConnectionString =#"Data Source=(local);Integrated Security=SSPI;" +"Initial Catalog=RV";
cn.Open();
string strSQL = "Select * From student";
SqlCommand myCommand = new SqlCommand(strSQL, cn);
using (SqlDataReader myDataReader = myCommand.ExecuteReader())
{
// Loop over the results.
while (myDataReader.Read())
{
Console.WriteLine("-> usn: {0}, name: {1}.",
myDataReader["usn"].ToString(),
myDataReader["name"].ToString()
);
}
}
Console.ReadLine();
}
}
}
}
You can use following connection string and try:
Integrated Security=SSPI;Persist Security Info=False;User ID=youruserid;Initial Catalog=databasename;Data Source=.\SQLEXPRESS
Also see the following link for connectionstring:
http://www.connectionstrings.com/sql-server/
I hope it will help you. :)
Let me know if it does not help you.

Use and call the connection string in the forms/ c#

I'm building desktop application using c# , I put the connection string in the app.config file like this
<connectionStrings>
<add name="ComputerManagement"
connectionString="Provider=Microsoft.ACE.OLEDB.12.0; Data Source=...;Initial Catalog=Computersh;Integrated Security=True"/>
</connectionStrings>
How I can call the connection string in the forms ?
You can get the connection string with ConfigurationManager:
using System.Configuration;
var connection = ConfigurationManager.ConnectionStrings["ComputerManagement"];
But you'll still need to use something to connect to the database with it, such as SqlConnection: http://msdn.microsoft.com/en-gb/library/system.data.sqlclient.sqlconnection.aspx
using System.Configuration;
using System.Data.SqlClient;
var connection = ConfigurationManager.ConnectionStrings["ComputerManagement"];
if (connection != null)
{
using (var sqlcon = new SqlConnection(connection.ConnectionString))
{
...
}
}
Reference System.Configuration and use
System.Configuration.ConfigurationManager
.ConnectionStrings["ComputerManagement"].ConnectionString
Like this:
var constring = ConfigurationManager.ConnectionStrings["ComputerManagement"].ConnectionString;
Also you have to add this using System.Configuration; :)
Using the ConfigurationManager should suffice:
var connection = ConfigurationManager.ConnectionStrings["ComputerManagement"];
Then, check for null, before accessing the actual string:
if (connection != null) {
var connectionString = connection.ConnectionString;
}

C# connection issue

My first issue: I am trying to establish connection to MySql database, but I keep getting error when I debug it with Visual Studio:"Connection must be valid and open."
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Threading;
using MySql.Data.MySqlClient;
using MySql.Data.Types;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
MySqlConnection conn;
string myConnectionString;
myConnectionString = "server=localhost;User Id=root;database=test3";
using (conn = new MySqlConnection(myConnectionString))
{
DateTime startTime = DateTime.Now;
MySqlCommand cmd = new MySqlCommand("SELECT * FROM department");
// sleep for 2.5s
Thread.Sleep(2500);
conn.Open();
var reader = cmd.ExecuteReader();
conn.Close();
}
}
}
My second issue: if there a way to display all this on a ASP.NET Web form (I want to leave code on server side), but display data something like ListView or GridView? Thanks in advance
You need to call conn.Open() before using it.
You forgot to attach your connection to the command:
cmd.Connection = conn;

Categories