OdbcDataAdapter Table Names - in C - c#

We got in-house software and I'm trying to connect to it via OdbcDataAdapter. It's a in-house database as well.
I have managed to connect to Db via excel but I'm having problems in C.
I'm not sure how to phrase correctly the table names. I have managed in excel as trial and error.
String from Excel:
queryString = "SELECT * FROM ADI.\"kzn-57 | 600 | Survey Disabled | Realtime\"";
ADI = databasename
Table = kz - 50 | 600 | Data Disabled | Realtime
I'm getting errors as below:
Unknown Table Name.
string connectionString = "dsn=int_db";
DataSet dataSet = new DataSet();
OdbcConnection connection =
new OdbcConnection(connectionString);
string queryString = "SELECT * FROM ADI.\"kz-50 | 0600 | Data Disabled | Realtime\"";
OdbcDataAdapter adapter =
new OdbcDataAdapter(queryString, connection);
connection.Open(); // Connection established ok
adapter.Fill(dataSet); // unknown tables error
Console.WriteLine(dataSet.GetXml());

Related

C# & Oracle Query Database with resepct to an organization

I am writing a C# application to pull specific items from an Oracle database. These items are specific to an organization inside of the Oracle E-Business Suite R12. The goal is to be able to query this but I have zero idea how!
The image below shows how the folder structure is laid out. As you can see targetted table is in
Data Table 2 - > Folder C - > Table Found
Once Targetted Table is Selected, a new dialog opens, for choosing an organization. For this example we will take Org 2
The C# Code I have written:
OracleConnection con = new OracleConnection();
// Oracle for items: Data Table 2 - > Folder C -> Targetted Table -> Item -> Find
con.ConnectionString = "Data Source=(DESCRIPTION =(ADDRESS = (PROTOCOL = TCP)(HOST = host.company.com)" +
"(PORT = 1521))(CONNECT_DATA = (SERVER = DEDICATED)(SERVICE_NAME = Data Table 2))); " +
"Password= WhiteRabbit1! ;User ID=Mr_Anderson";
con.Open();
Console.WriteLine("Connected to Oracle" + con.ServerVersion);
OracleCommand cmd = new OracleCommand();
cmd.Connection = con;
cmd.CommandText = "SELECT [Level], [Item], [Description] FROM [Targetted Table]";
cmd.CommandType = CommandType.Text;
OracleDataReader dr = cmd.ExecuteReader();
while (dr.Read())
// Add data
Which outputs the error:
Oracle.DataAccess.Client.OracleException: 'ORA-12541: TNS:no listener'
At the Line: con.Open();
EDIT: Changed HOST = host.company.com to HOST = host.company.com\ and we get a new error output!
Oracle.DataAccess.Client.OracleException: 'ORA-12545: Connect failed because target host or object does not exist'
I am trying to follow this guide: https://o7planning.org/en/10509/connecting-to-oracle-database-using-csharp-without-oracle-client#a1814792
But not sure what step messed up the code. My guess is the port, but I don't know where to look for that. Saw an article that said use 1521 for database access

C# | MySql query working in DB not working in application

I have this query:
string query = "SELECT afspraak_locatie FROM Afspraak WHERE date(datum) = '" + datum +"'";
The final query will look like this:
SELECT afspraak_locatie FROM Afspraak WHERE date(datum) = '2016-06-16'
When i execute the query in my PHPMYADMIN it returns the row. But when i do it in C# it says my MySqldatareader is empty
Here is the code i use for that:
MySqlCommand cmd1 = new MySqlCommand(query1, connection);
cmd1.CommandType = CommandType.Text;
using (MySqlDataReader reader1 = cmd1.ExecuteReader())
{
while (reader1.Read())
{
result1.Add(reader1.GetString(0));
}
reader1.Close();
}
cmd1.Cancel();
When this gets executed it will give a System.NullreferenceException on the while(reader1.read) part. Any solutions?
Schema and data loaded:
create table Afspraak
(
id int auto_increment primary key,
afspraak_locatie varchar(100) not null, -- just an example (we don't know your datatype)
datum datetime not null -- you said it was a datetime in a comment under your question
);
insert Afspraak (afspraak_locatie,datum) values
('Rome','2016-06-14 13:55:55'),
('London','2016-06-15 15:12:12'),
('Cairo','2016-06-16 07:00:33'),
('Boston','2016-06-17 01:30:00');
select * from afspraak;
+----+------------------+---------------------+
| id | afspraak_locatie | datum |
+----+------------------+---------------------+
| 1 | Rome | 2016-06-14 13:55:55 |
| 2 | London | 2016-06-15 15:12:12 |
| 3 | Cairo | 2016-06-16 07:00:33 |
| 4 | Boston | 2016-06-17 01:30:00 |
+----+------------------+---------------------+
GUI Layer:
private void button1_Click(object sender, EventArgs e)
{
myDB.FindThatRow("2016-06-16"); // get data
}
DB Layer:
public void FindThatRow(string theDate)
{ // or all those rows
//
using (MySqlConnection lconn = new MySqlConnection(connString))
{
lconn.Open();
using (MySqlCommand cmd = new MySqlCommand())
{ //
cmd.Connection = lconn;
cmd.CommandText = #"select id,afspraak_locatie FROM Afspraak WHERE date(datum) = #pTheDate";
cmd.Prepare();
cmd.Parameters.AddWithValue("#pTheDate", theDate);
using (MySqlDataReader rs = cmd.ExecuteReader())
{ //
while (rs.Read())
{
int qId = (int)rs.GetInt32("id");
string sViewIt = rs.GetString("afspraak_locatie");
}
}
}
}
}
It found the data:
Use the using blocks as recommended by everyone. Bind your parameters.
The reasons why one should steer toward data bindings, versus string concatenation as seen in your attempt, include losing the functionality of what binding offers as seen in Configuring Parameters and Parameter Data Types and other links near or off that topic. And, it turns querying into the mess seen in PHP with concatenation which steered their modern usage toward parameter data bindings too.
Imagine how difficult and debug-intensive the following query would be without bindings:
Sql Injection Attacks:
Parameter binding protects you from such attacks, unlike your method of concat. See the following question including this answer for stored procedure usage.

Inserting data after checking if table is empty

I have a server program that will store certain data sent by the client. One data is the client's hostname. The server will check if the hostname exist, if not then it will insert that new data. It should look like this.
hostname_id | hostname
------------------------
1 | Admin
2 | Guest_PC
3 | Bob_PC2
My problem is it won't store the newly inserted data. It keeps on returning zero but not storing anything. Here is my code.(Edited to correct version)
string constring = "Database=chtbuster;Data Source=localhost;User Id=root;Password=''";
string count1 = "SELECT COUNT(hostName) FROM chtbuster.hostnametable WHERE hostName=#machineName ";
using (MySqlConnection conDataBase = new MySqlConnection(constring))
{
MySqlCommand cmd1Database = new MySqlCommand(count1, conDataBase);
conDataBase.Open();
long count = (long)cmd1Database.ExecuteScalar();
if (count == 0)
{
string insert_ht = "INSERT INTO chtbuster.hostnametable(hostName) VALUES(#machineName);";
MySqlCommand cmd5Database = new MySqlCommand(insert_ht, conDataBase);
cmd5Database.Parameters.AddWithValue("#machineName", machineName);
cmd5Database.ExecuteNonQuery();
//*test* output.Text += "\n Empty " + count;
}
else
{
//not empty, insert other data
}
}
I have coded PHP database before and is new to C# database, I'm quite confused. Please help. Thank you.
You can do this in one step with EXISTS:
IF NOT EXISTS (SELECT hostName FROM chtbuster.hostnametable WHERE hostName=#machineName)
INSERT INTO chtbuster.hostnametable(hostName_id) VALUES(#machineName);
As mentioned in the comments, you need to execute the query to get a result.

How to Insert whole DataTable into Sql table At once in C#

I have excel sheet (named as $Sheet1) and sql table(named as Users) with same Formate which is given below
ID | UserName | FirstName | LastName | DateOfBirth |
1 | robert | robert | poinan | 1984 |
2 | joy | joy | rob | 1990 |
I Have read the whole excel sheet data in DataSet (Named as 'ds') now I want to insert the whole DataSet (which is 'ds') in sql table (which is 'Users')
I am using for loop (can also use foreach loop) to insert 'ds' (DataSet) rows one by one into Users (Sql table) table
sqlConn.Open();
for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
{
SqlCommand cmd = new SqlCommand("INSERT INTO [Users] ([ID],[UserName],[FirstName],[LastName],[DateOfBirth]) VALUES(#ID,#UserName,#FirstName,#LastName,#DateOfBirth))", sqlConn);
cmd.Parameters.AddWithValue("#ID", ds.Tables[0].Rows[i][0].ToString());
cmd.Parameters.AddWithValue("#UserName", ds.Tables[0].Rows[i][1].ToString());
cmd.Parameters.AddWithValue("#FirstName", ds.Tables[0].Rows[i][2].ToString());
cmd.Parameters.AddWithValue("#LastName", ds.Tables[0].Rows[i][3].ToString());
cmd.Parameters.AddWithValue("#DateOfBirth", ds.Tables[0].Rows[i][4].ToString());
cmd.ExecuteNonQuery();
}
}
sqlConn.Close();
in this code I am facing a lot of problems one of these is, if there is any error in inserting the row the program stop but the rows that are inserted before are exists in the sql database next time when I try to run this program the data rows are duplicated.
I have millions of records. if I want to check the data row in sql table it takes a lot of time to execute the whole process.
My quetion is. Is there any way to insert the whole 'DataTable (which is in DataSet)' into Users Table at once
Something Like This
INSERT INTO [Users](ID, FirstName,LastName,DateOfBirth)
SELECT ID, FirstName,LastName,DateOfBirth FROM ds.Tables[0]
;
This is the approach given in MSDN(https://msdn.microsoft.com/en-us/library/ex21zs8x(v=vs.110).aspx). Make a DT and pass the DT as parameter to BulkCopy.
DataTable dt = new DataTable();
dt.Columns.Add("FieldName", typeof(System.Decimal));

How to create a join across two foxpro databases using the MS Ole DB provider?

Question:
I am working with existing commercial MS Visual Foxpro application, and need to extract data from the database directly using a c# application. Unfortunately, not all of the tables are stored in the same database, some of the records are stored in a database broken down by year. How do I create a query against these two databases using a single join?
I am using Microsoft's OLE DB Provider for Visual FoxPro 9.0 (SP2)
More Detail:
Essentially, the customer information is stored in one database, and the customer purchase history is stored a database broken down by year. So I am trying to create a simple query to print out customers and their most recent purchase from this year.
In graphical form, the file structure of the db looks like this:
Data\
+-2009\
| +-MyDB.dbc
| +-Sales.dbf
+-2010\
| +-MyDB.dbc
| +-Sales.dbf
+-MyDB.dbc
+-Customers.dbf
Currently I can connect to each DB individually, and query them:
// This works to connect to the customer DB
string connectionPath1 = #"Provider=vfpoledb.1;Data Source=E:\Data\MyDB.dbc";
OleDbConnection conn1 = new OleDbConnection(connectionPath1);
OleDbCommand command1 = new OleDbCommand(#"SELECT * FROM Customers", conn1);
OleDbDataReader reader1 = command1.ExecuteReader();
// This works to connect to the annual sales record DB
string connectionPath2 = #"Provider=vfpoledb.1;Data Source=E:\Data\2010\MyDB.dbc";
OleDbConnection conn2 = new OleDbConnection(connectionPath2);
OleDbCommand command2 = new OleDbCommand(#"SELECT * FROM Sales", conn2);
OleDbDataReader reader2 = command2.ExecuteReader();
What I can't do is execute my join statement:
//How do I do this?
OleDbConnection connMagic = new OleDbConnection(connectionPath1, connectionPath2); //non-valid code
OleDbCommand commandIWant = new OleDbCommand(#"SELECT Customers.Name, Sales.Item, Sales.Date FROM Customers LEFT JOIN Sales ON (Customers.ID=Sales.CustomerID)", connMagic);
OleDbDataReader reader3 = commandIWant.ExecuteReader();
If the directory structure is as you indicate... where the different years are all UNDER the parent common, you can query to all of them directly just by including the relative path...
select
a1.Whatever,
b1.Sales1
from
Customers a1,
2009\Sales b1
where
a1.CustomerID = b1.CustomerID
union all
select
a1.Whatever,
b1.Sales1
from
Customers a1,
2010\Sales b1
where
a1.CustomerID = b1.CustomerID
union ...
you dont even have to qualify the actual DBC either, the OleDB should auto-detect it, but having it included wouldn't hurt as your original samples indicate...
Add both FoxPro tables to a DataSet either with seperate OleDbConnection objects or by reusing one OleDbConnection object. Then add a DataRelation between the 2 DataTables.
You could also try adding the DBC name to your SQL SELECT:
"SELECT c.Name, s.Item, s.Date FROM MyDB!Customers c LEFT JOIN 2009\MyDB!Sales s ON (c.ID=s.CustomerID)"

Categories