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
Related
i have a problem with making a local database into my c# project and creating it..
I tried first with making a Microsoft Sql Server but the problem is that i need to make app which should run on every pc. The app should input data from user , and collect it to the database, and on every start of program, the database should be filled with the leftover of earlier input.. What you suggest me to do?
First to connect your c# application with sqlite you should start with getting connection string
private static string executableLocation = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
private static string oldconnectionstring = Path.Combine(executableLocation, "YourDB.db");
private static string connectionString = "Data Source =" + oldconnectionstring.ToString();
After getting connection, to add your input to database follow below steps
using (SQLiteConnection conn = new SQLiteConnection(connectionString))
{
//Open connection to DB
conn.Open();
//Query to be fired
string sql = "Your Query to insert rows";
//Executing the query
using (SQLiteCommand cmd = new SQLiteCommand(sql, conn))
{
//Executing the query
cmd.CommandText = sql;
cmd.ExecuteNonQuery();
}
//Close connection to DB
conn.Close();
}
I'm developing an application for my WindowsCE packect PC(.netCF35) to read some parameters and record them in my SQLite database in Visual Studio 2008. I knew that I need to add SQLite references to my application (I had a succeed experience for my windows 7 application). So I downloaded related files from http://system.data.sqlite.org/index.html/doc/trunk/www/downloads.wiki and I just could add System.Data.SQLite.dll (I couldn't add SQLite.Interop.102.dll to my references). Now when I run my application, I can't add any data to my database and it seems cmdwrite.ExecuteNonQuery(); doesn't work correct. I need to say my table name and structure is correct(I'm sure). You can see my code as follow:
SQLiteConnection con = new SQLiteConnection("Data Source=AMI.sqlite;Version=3;");
public bool Insert(string Meter_ID, string type, string readout, string timestamp)
{
sqlwrite = "INSERT INTO meters (id,type,val,timestamp) VALUES(?,?,?,?)";
try
{
SQLiteCommand cmdwrite = new SQLiteCommand(sqlwrite, con);
cmdwrite.Parameters.AddWithValue("#id", Meter_ID);
cmdwrite.Parameters.AddWithValue("#type", type);
cmdwrite.Parameters.AddWithValue("#val", readout);
cmdwrite.Parameters.AddWithValue("#timestamp", timestamp);
con.Open();
dbstate = "3";
cmdwrite.ExecuteNonQuery();
dbstate = "4";
con.Close();
return true;
}
catch
{
con.Close();
return false;
}
}
Insert("123", "456", "789", "123");
Does anybody have any experience to work with SQLite database in WindowsCE?
I have create a simple login application using the C#.net.
I have created database test in which I have created table called as login.
Table: Login contains:
create table login
(
name varchar(20),
pass varchar(20)
)
Here is the login button code which I have written in the C#.net:
private void BtnLogin_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection();
con.ConnectionString = "Data Source=ServerName;Initial Catalog=test;Integrated Security=True";
con.Open();
SqlDataReader dr = null;
SqlCommand cmd = new SqlCommand("Select * from login", con);
dr = cmd.ExecuteReader();
int count = 0;
while (dr.Read())
{
if (textBox1.Text == dr[0].ToString() && textBox2.Text == dr[1].ToString())
{
count = count + 1;
}
else
{
count = count + 0;
}
}
if (count == 1)
{
MessageBox.Show("Success");
}
else
{
MessageBox.Show("Fail");
}
}
Note: The above example works fine for me if I installed the Visual Studio 2010 and SQL Server Management studio in a single machine.
But
I want to run the above application in the machine where only Visual Studio 2010 is installed not SQL Server Management Studio.
Is it possible?
Data Source=ServerName;Initial Catalog=test;Persist Security Info=True;User ID=YourUserId;Password=YourPassword
Also you have to instal .net framework on your local machine
The SqlClient types that you are using (SqlConnection, SqlDataReader, and so on) are defined in System.Data.dll (you can see this by going to the MSDN docs, the assembly is documented just above the big 'Syntax' heading') which is part of the .NET Framework. So as long as you have .NET Framework installed on a machine, you do not need any additional dependencies such as Visual Studio or SSMS.
I am trying to rebuild an application that originally used sqlite to now use 'localdb'. (I want an application that can create its own database locally and at runtime without requiring a pre-installed instance of sql server or sql express on the target machine)
I want to move away from using a 'third party' library (sqlite) as experience has told me it can be a pain to get it working from scratch, and towards something supposedly more straightforward to get up and running from scratch.
Using code copied (and slightly modified) from the web I have managed to create an mdf file dynamically/programmatically, but I am puzzled by what happens if I run it more than once, even if I choose a new filename each time. Namely it seems to somehow keep the changes/additions made on each run. Below is the relevant code...
public partial class Form1 : Form
{
SqlConnection conn;
public void CreateSqlDatabase(string filename)
{
string databaseName =
System.IO.Path.GetFileNameWithoutExtension(filename);
conn = new SqlConnection(
String.Format(
#"Data Source=(LocalDB)\v11.0;Initial Catalog=master;Integrated Security=True"
));
conn.Open();
using (var command = conn.CreateCommand())
{
command.CommandText =
String.Format(
"CREATE DATABASE {0} ON PRIMARY (NAME={0}, FILENAME='{1}')"
, databaseName, filename);
command.ExecuteNonQuery();
command.CommandText =
String.Format("EXEC sp_detach_db '{0}', 'true'", databaseName);
command.ExecuteNonQuery();
}
conn.Close();
}
private void button1_Click(object sender, EventArgs e)
{
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
CreateSqlDatabase(openFileDialog1.FileName);
}
}
private void button2_Click(object sender, EventArgs e)
{
conn.Open();
SqlCommand comm = conn.CreateCommand();
comm.CommandText =
"create table mytable (id int, name nvarchar(100))";
comm.ExecuteNonQuery();
comm.CommandText =
"insert into mytable (id,name) values (10,'testing')";
comm.ExecuteNonQuery();
comm.CommandText = "select * from mytable";
SqlDataReader reader = comm.ExecuteReader();
while (reader.Read())
{
textBox1.Text +=
reader["id"].ToString() + ", " + reader["name"].ToString() + "\r\n";
}
conn.Close();
}
}
If I run the app once It runs through fine.
If I run the app a second time, and choose a different filename for the database it tells me 'mytable' already exists.
If I comment out the create table code it runs, but the select query returns multiple rows indicating multiple inserts (one for each time the app runs)
I am just seeking to understand why this happens. Do I need to delete database/table each time if I want the app to behave as if it has created the database/table from scratch on each subsequent run?
You have initial catalog 'master' in your connection string. Are you sure you haven't created the tables in the master database instead of the newly created database?
After the creation & detach of the database file, you could try and change your connection to:
SqlConnection con = new SqlConnection(#"Data Source=(LocalDB)\v11.0;Integrated Security=True;AttachDbFilename=c:\xxx\xxx\xxx.mdf");
At first it wrote this exception:
"SQL Server Compact is not intended for ASP.NET development."
and then I added:
AppDomain.CurrentDomain.SetData("SQLServerCompactEditionUnderWebHosting", true);
to the Global.aspx and it fixed it.
But now when I try to open the SqlCeConnection it gives me this exception:
Incompatible Database Version. If this was a compatible file, run
repair. For other cases refer to documentation. [ Db version =
4000000,Requested version = 3505053,File name =
\?\C:\Users\gal\Documents\Visual Studio
2012\WebSites\Project_Level_4\DB\PhoneBookWeb.sdf ]
Can anyone please help ?
Install the SQL CE 4.0 package: http://www.microsoft.com/en-us/download/details.aspx?id=17876
Try adding the reference in your IDE to "C:\Program Files (x86)\Microsoft SQL Server Compact Edition\v4.0\Desktop\System.Data.SqlServerCe.dll"
Add the using clauses:
using System.Data.SqlServerCe;
using System.IO;
Then try something like this:
string connectionString;
string fileName = "test.sdf";
string password = "test";
if (File.Exists(fileName))
File.Delete(fileName);
connectionString = string.Format("DataSource=\"{0}\"; Password='{1}'", fileName, password);
SqlCeConnection conn = null;
try {
SqlCeEngine engine = new SqlCeEngine(connectionString);
engine.CreateDatabase();
conn = new SqlCeConnection(connectionString);
conn.Open();
SqlCeCommand cmd = conn.CreateCommand();
cmd.CommandText = "CREATE TABLE myTable (col1 int, col2 ntext)";
cmd.ExecuteNonQuery();
}
catch(Exception ex)
{
Console.WriteLine(ex.ToString());
}
finally {
conn.Close();
}