How to connect an oracle database in C #? - c#

Since monday I followed several tutorials to establish connection to my Oracle database.
I downloaded at http://www.oracle.com/technetwork/database/windows/downloads/index-090165.html
and launched "install.bat".
In visual studio, in reference section I browsed the directory that I downloaded and found "Oracle.DataAccess.dll" in the following path "\odp.net4\odp.net\bin\4".
When I run my code I get the following error:
External component has thrown an exception
Furthermore I have the following warning :
Warning 1 There is a difference between the project processor
architecture being generated "MSIL" and the reference processor
architecture "Oracle.DataAccess, Version = 4.121.2.0, Culture =
neutral, PublicKeyToken = 89b483f429c47342, processorArchitecture =
x86 "," AMD64 ". This difference can lead to runtime problems.
I don't understand this error so I hope you will be able to help me.
Or if you know a better way to connect to a database oracle, I will be interested.
namespace WindowsFormsApplication2
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
OraTest oraTest = new OraTest();
oraTest.Connect();
oraTest.Close();
MessageBox.Show("Connecté");
}
}
}
using Oracle.DataAccess.Client;
namespace WindowsFormsApplication2
{
class OraTest
{
OracleConnection con;
public void Connect()
{
con = new OracleConnection();
con.ConnectionString = "User Id=<username>;Password=<password>;Data Source=<datasource>";
con.Open();
Console.WriteLine("Connected to Oracle" + con.ServerVersion);
}
public void Close()
{
con.Close();
con.Dispose();
}
}
}

I suggest to use Official Oracle ODP.NET
In Nuget type:
Install-Package Oracle.ManagedDataAccess

Related

Any C# WinApplication with Install Sheild Building to .exe with SqlServer Database

i have compile the application to Setup.exe with Install Sheild in Visual studio 2015 with SQL server 2012. The application work on my computer but when i transfer Setup.exe it to clients computer it didnt work generate problem with client computer.
Need A way to handle the application with
I have attached the database to SQLSERVER Managment studio.
I have
change configuration File Data Source=""to client computer Address
but still not working.
public static string GetConnection()
{
return ConfigurationManager.ConnectionStrings["MyCon"].ConnectionString;
}
SqlConnection con = new SqlConnection(GetConnection());
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
con.Open();
SqlCommand cmd = new SqlCommand("Select EmpID from RegForm",con);
int i= Convert.ToInt32(cmd.ExecuteScalar());
if(i!=0)
{
MessageBox.Show("value type is " + i);
con.Close();
MessageBox.Show("Connection is closed ");
}
}
I just want that this compile application Start working with setting path in configuration DataSource Attribute nd the programming start working with Active Database

How to connect to database in C# using SqlConnection object?

How can I connect to a remote or local database using simple SqlConnection object? I learned to do it this way, but my connection is failing. I read about creation of connection string from this page:
https://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlconnection.connectionstring(v=vs.110).aspx
My code:
using System.Data.SqlClient;
namespace SyncApp_BuiltInProviders
{
public partial class Form1 : Form
{
private void btnSynchronize_Click(object sender, EventArgs e)
{
SqlConnection source_conn = new SqlConnection();
source_conn.ConnectionString ="Server=localhost;Database = ptls; UID = root;Password = ODYSSEY99GRANITE;";
source_conn.Open();
}
}
}
As from your comment in another answer it is clear that you are using the wrong classes. The SqlConnection is a class specialized in connecting to Sql Server/Sql Server Express/LocalDb. It cannot work against a MySql
If you use MySql then you need to download and install the MySql Connector for NET from here.
After that, you need to reference the MySql.Data.dll and add a
using MySql.Data.MySqlClient;
to all the source files that interact with the database.
Finally, all the classes used to work with the database, should be the ones provided by the MySql NET Connector.
They are prefixed with MySql..... (MySqlConnection, MySqlCommand, MySqlDataReader etc.)
If you are used SQL Database, it seems to me that, you have not set username and password. If you have not set username and password then try this.
private void btnSynchronize_Click(object sender, EventArgs e)
{
SqlConnection db_connect= new SqlConnection();
db_connect.ConnectionString ="Server=[your local pc connection name, it is not local host.];Database=[database_name];Trusted_Connection=true";
db_connect.Open();
}
If you use MySql then
private void btnSynchronize_Click(object sender, EventArgs e)
{
//Create a MySQL connection string.
string connectionString="Server=localhost;Database[database_name];Uid=root;Password =your password; ";
MySqlConnection db_connect= new MySqlConnection(connectionString);
db_connect.Open();
}
Finally use following name space
using MySql.Data.MySqlClient;

C# how to connect WPF and SQLITE database easiest way

New to wpf and sqlite. I just want an internal database for my project. I want this project to be able to used by others so I cannot use mysql as a database. So I search for internal databases and decided to try sqlite. Im finding tutorial but they are really confusing. I'm familiar in database I know the queries but now I just need to know what are the necessary things to setup to start the connection between WPF and sqlite. Below is my code(I create a different class for my sqlite connection):
sqlite class
using System.Data.SQLite;
namespace StartMyApps
{
class StartMyAppDb_sqlite
{
public SQLiteConnection myConn;
public SQLiteCommand myComm;
public SQLiteDataReader myReader;
public void openConnection(string query)
{
myConn = new SQLiteConnection("Data Source=StartMyApplication.sqlite;Version=3;");
myConn.Open();
myComm = new SQLiteCommand(query, myConn);
myComm.ExecuteNonQuery();
myReader = myComm.ExecuteReader();
}
}
}
Main class (has a button to trigger the connection and will pass a query)
private void hide_btn_Click(object sender, RoutedEventArgs e)
{
sqliteDB.openConnection("select *from application where app_id='1' and app_name='chrome.exe';");
bool hasAccount = false;
while (sqliteDB.myReader.Read())
{
hasAccount = true;
}
if (hasAccount == false)
{
MessageBox.Show("Logged in");
}
else if (hasAccount == true)
{
MessageBox.Show("Username invalid");
}
}
With this code I got an error says
"An unhandled exception of type 'System.DllNotFoundException' occurred
in System.Data.SQLite.dll Additional information: Unable to load DLL
'SQLite.Interop.dll': The specified module could not be found.
(Exception from HRESULT: 0x8007007E)"
Please help. Any help will be much appreciated THANKS!
I think this is what your looking for: Unable to load DLL 'SQLite.Interop.dll'
Assuming you have:
SQLite installed (correct version for windows)
Appropriate references
Follow below steps:
Add 2 folders in the project and name it x64 and x86.
Add SQLite.interop.dll for x64 and x86 respectively(google for the same)
In SQLite.interop.dll properties, set
"Build Action" --> Content
and "Copy to Output directory" -> Copy Always/Copy if newer.

Connecting to Oracle Database through C#?

I need to connect to a Oracle DB (external) through Visual Studio 2010. But I dont want to install Oracle on my machine.
In my project I referenced: System.Data.OracleClient. But its not fulfilling the need.
I have an "Oracle SQL Developer IDE" in which I run SQL queries against oracle db.
I have this code so far:
private static string GetConnectionString()
{
String connString = "host= serverName;database=myDatabase;uid=userName;pwd=passWord";
return connString;
}
private static void ConnectingToOracle()
{
string connectionString = GetConnectionString();
using (OracleConnection connection = new OracleConnection())
{
connection.ConnectionString = connectionString;
connection.Open();
Console.WriteLine("State: {0}", connection.State);
Console.WriteLine("ConnectionString: {0}",
connection.ConnectionString);
OracleCommand command = connection.CreateCommand();
string sql = "SELECT * FROM myTableName";
command.CommandText = sql;
OracleDataReader reader = command.ExecuteReader();
while (reader.Read())
{
string myField = (string)reader["MYFIELD"];
Console.WriteLine(myField);
}
}
}
So far I read these blogs:
http://st-curriculum.oracle.com/tutorial/DBXETutorial/index.htm
http://blogs.msdn.com/b/kaevans/archive/2009/07/18/connecting-to-oracle-from-visual-studio.aspx
So far I have not downloaded anything from Oracle. What steps should I take to make this happen?
First off you need to download and install ODP from this site
http://www.oracle.com/technetwork/topics/dotnet/index-085163.html
After installation add a reference of the assembly Oracle.DataAccess.dll.
Your are good to go after this.
using System;
using Oracle.DataAccess.Client;
class OraTest
{
OracleConnection con;
void Connect()
{
con = new OracleConnection();
con.ConnectionString = "User Id=<username>;Password=<password>;Data Source=<datasource>";
con.Open();
Console.WriteLine("Connected to Oracle" + con.ServerVersion);
}
void Close()
{
con.Close();
con.Dispose();
}
static void Main()
{
OraTest ot= new OraTest();
ot.Connect();
ot.Close();
}
}
You can use Oracle.ManagedDataAccess NuGet package too (.NET >= 4.0, database >= 10g Release 2).
Using Nuget
Right click Project, select Manage NuGet packages...
Select the Browse tab, search for Oracle and install Oracle.ManagedDataAccess
In code use the following command (Ctrl+. to automatically add the using directive).
Note the different DataSource string which in comparison to Java is
different.
// create connection
OracleConnection con = new OracleConnection();
// create connection string using builder
OracleConnectionStringBuilder ocsb = new OracleConnectionStringBuilder();
ocsb.Password = "autumn117";
ocsb.UserID = "john";
ocsb.DataSource = "database.url:port/databasename";
// connect
con.ConnectionString = ocsb.ConnectionString;
con.Open();
Console.WriteLine("Connection established (" + con.ServerVersion + ")");
The next approach work to me with Visual Studio 2013 Update 4
1- From Solution Explorer right click on References then select add references
2- Assemblies > Framework > System.Data.OracleClient > OK
and after that you free to add using System.Data.OracleClient in your application and deal with database like you do with Sql Server database except changing the prefix from Sql to Oracle as in SqlCommand become OracleCommand for example to link to Oracle XE
OracleConnection oraConnection = new OracleConnection(#"Data Source=XE; User ID=system; Password=*myPass*");
public void Open()
{
if (oraConnection.State != ConnectionState.Open)
{
oraConnection.Open();
}
}
public void Close()
{
if (oraConnection.State == ConnectionState.Open)
{
oraConnection.Close();
}}
and to execute some command like INSERT, UPDATE, or DELETE using stored procedure we can use the following method
public void ExecuteCMD(string storedProcedure, OracleParameter[] param)
{
OracleCommand oraCmd = new OracleCommand();
oraCmd,CommandType = CommandType.StoredProcedure;
oraCmd.CommandText = storedProcedure;
oraCmd.Connection = oraConnection;
if(param!=null)
{
oraCmd.Parameters.AddRange(param);
}
try
{
oraCmd.ExecuteNoneQuery();
}
catch (Exception)
{
MessageBox.Show("Sorry We've got Unknown Error","Connection Error",MessageBoxButtons.OK,MessageBoxIcon.Error);
}
}
Basically in this case, System.Data.OracleClient need access to some of the oracle dll which are not part of .Net. Solutions:
Install Oracle Client , and add bin location to Path environment varaible of windows
OR
Copy
oraociicus10.dll (Basic-Lite version) or aociei10.dll (Basic version),
oci.dll, orannzsbb10.dll and oraocci10.dll from oracle client installable folder to bin folder of application so that application is able to find required dll

can't find the logical error in c# asp.net below

I wrote this code to get data from mysql database using odbc connection. Its giving no error but no output as well. Am not able to find what the matter is.
public partial class Members : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
DataTable table = new DataTable();
string conString = WebConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
try
{
using (OdbcConnection con = new OdbcConnection(conString))
{
con.Open();
// We are now connected. Now we can use OdbcCommand objects
// to actually accomplish things.
using (OdbcCommand com = new OdbcCommand("SELECT * FROM abc", con))
{
using (OdbcDataAdapter ad = new OdbcDataAdapter(com))
{
ad.Fill(table);
}
}
con.Close();
}
}
catch (Exception ei)
{
Label1.Text = ei.Message;
}
GridView1.DataSource=table;
GridView1.DataBind();
}
}
In web.config do you have a connectionString? Please check that.
If not you can add datasource from visual studio designer and it will ask to add connection string in one of the steps .At the end you can remove datasource from designer but still have connectionstring in web.config file .And in your code behind can you try this
string SQL_CONNECTION_STRING = System.Configuration.ConfigurationManager.ConnectionStrings["SqlConnectionTest"].ConnectionString;
where "SqlConnectionTest" is the name of connection string in web.config.
The problem was that I converted a vb project just by replacing the c# file with the vb ones to make it a c# project, and this created this whole mess.The code work perfectly fine when done on a new projects.

Categories