How to get data table without using database name in query - c#

I tried to get table which has top record from Oracle database through ODBC driver. For this, I am using below code.
OdbcConnectionStringBuilder builder = new OdbcConnectionStringBuilder();
builder.ConnectionString = "Driver={Oracle in OraClient11g_home1};Dbq=localhost;Uid=system;Pwd=abc;Database = NORTHWIND";
OdbcConnection con = new OdbcConnection();
con.ConnectionString = builder.ConnectionString;
con.Open();
string query = "SELECT \"NORTHWIND\".\"ORDERS\".\"ID\" AS \"My field id\" FROM \"NORTHWIND\".\"ORDERS\" WHERE ROWNUM = 1";
OdbcCommand cmd = new OdbcCommand(query,con);
var k = cmd.ExecuteReader();
var datatable = new DataTable();
datatable.Load(k);
con.Close();
The above code is working fine for me. I need to execute query without database name. Here database name is NORTHWIND. But If I am using query without database name like "SELECT \"ORDERS\".\"ID\" AS \"My field id\" FROM \"ORDERS\" WHERE ROWNUM = 1"
I got an exception "table or view does not exist."
Even if my connectionstring has database name, I got this exception.
Can anyone explain me why I got the above exception when using query without database name?

Change your connection string to this-
builder.ConnectionString = "Driver={Oracle in OraClient11g_home1};Dbq=localhost;Uid=system;Pwd=abc;Data Source = NORTHWIND;";
Referrences-
https://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlconnectionstringbuilder.initialcatalog(v=vs.110).aspx
http://www.c-sharpcorner.com/UploadFile/nipuntomar/connection-strings-for-oracle/
https://docs.oracle.com/database/121/ODPNT/featConnecting.htm#ODPNT199

Related

Parameterized Query Build Error

Why aren't my parameterized variables being added to my Sql query?
I have two parametrized variables set by combobox.text which is selected by the end user.
I get the error below when trying to use a query that uses a parameterized variable.
Additional information: Must declare the scalar variable "#username"
Am I missing something?
Example Query
SQL = "SELECT stationID, LocationName, plandate, username, status FROM dbo.joblist WHERE username = #username and status = #status";
Code Snippet
//Decide what query
String SQL = SQLSelection();
//Connection String
String ConnString = "Data Source=dbsqlexpress; Provider=SQLOLEDB; Initial Catalog=Data; User ID=mobile; Password=PW";
//Create and initalize Oledbconnection object and pass connection string into it.
OleDbConnection con = new OleDbConnection(ConnString);
//open connection to database
con.Open();
//create adapter that sits inbetween dataset and datbase
OleDbDataAdapter adapter = new OleDbDataAdapter();
adapter.SelectCommand = new OleDbCommand(SQL,con);
adapter.SelectCommand.Parameters.Add("#username", OleDbType.VarChar).Value = auditorCmb.Text;
adapter.SelectCommand.Parameters.Add("#status", OleDbType.VarChar).Value = statusCmb.Text;
//Create dataset
DataSet dataset = new DataSet();
using (DataTable dt = new DataTable())
{
adapter.Fill(dt);
dataGridView1.AutoResizeColumns();
dataGridView1.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells;
con.Close();
dataGridView1.DataSource = dt;
int rowCount = rowCount = dt.Rows.Count;
label10.Text = rowCount.ToString("n0");
}
}
With OLE DB (and ODBC), you need to specify ? as parameter markers in the SQL statement. These are then mapped by ordinal according to the order parameters were mapped to the collection.
SQL = "SELECT stationID, LocationName, plandate, username, status FROM dbo.joblist WHERE username = ? and status = ?;";
Avoid using OLE DB and ODBC in .NET applications. The .Net Provider for SQL Server (a.k.a SqlClient) will provide better performance from .Net Applications. Also, Microsoft has announced deprecation of OLE DB for relational database access in SQL Server.
The OLE DB .NET Provider does not support named parameters for passing parameters to an SQL statement or a stored procedure called by an OleDbCommand when CommandType is set to Text. In this case, the question mark (?) placeholder must be used. For example:
SELECT * FROM Customers WHERE CustomerID = ?
MSDN:OleDbCommand.Parameters Property

C# - OleDB Systax Error in From Clause

I am using Microsoft Access to create a "Desktop Database" and saved it as "new.mdb" into my C# Debug folder.
However, upon using the SELECT statement, my C# project throws an Exception.
This is my database
And this is my code
conn = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=new.mdb");
conn.Open();
dataset = new DataSet();
string sqlStatement = "SELECT * FROM User";
dbAdapter = new OleDbDataAdapter(sqlStatement, conn);
oOrderDetailsCmdBuilder = new OleDbCommandBuilder(dbAdapter);
dbAdapter.Fill(dataset);
contactsTab = dataset.Tables[0];
contactsTab.TableName = "User";
rows = contactsTab.Rows;
The error upon executing that code is
Syntax error in FROM clause.
However, the query looks fine. Is there anything wrong?
Thanks!
EDIT :
OleDbCommand.ExecuteNonQuery (Example : Creating new table) works for this. I'm not sure why SELECT statement doesn't :/
User is a reserved keyword in SQL. So write SQL like below
string sqlStatement = "SELECT * FROM [User]";

How to Export Data from SQL server Compact To Access MDB

I need a solution to transfer all data from SQL Server CE to Access mdb database.
I tried this approach http://www.codeproject.com/Answers/483989/HowplustoplusExportplusSQLplusTablesplusToplusAcce#answer2 (solution # 2) but getting an error "No database specified in connection string or IN clause."
The code works if I connect to non-compact SQL server.
I guess the problem is with connection string in IN clause but I cannot figure out how to change it.
Here is my code:
private void ExportTable(string tableName, string source, string destination)
{
var connStr = string.Format("Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0}", destination);
var cmdText = string.Format("SELECT * INTO {0} FROM [{0}] IN ''[Data Source={1};Max Database Size='4000';Persist Security Info=False;];", tableName, source);
using (var conn = new OleDbConnection(connStr))
{
conn.Open();
using (var cmd = new OleDbCommand(cmdText, conn))
{
cmd.ExecuteNonQuery(); // error on this line
}
conn.Close();
}
}
The connection string: Data Source={1};Max Database Size='4000';Persist Security Info=False; working ok when I connect to the database directly.
UPDATE: Apparently the format of the source DB in IN Clause should be as following:
[type; DATABASE = path]
(see: http://answers.microsoft.com/en-us/office/forum/office_2010-access/access-2010-runtime-error-3170-could-not-find/0b085797-618a-488f-b1b4-30af00f04b3f)
When I use
var cmdText = string.Format("SELECT * INTO {0} FROM [{0}] IN ''[SqlServer CE; DATABASE={1}];", tableName, source);
I am getting different error: Could not find installable ISAM.
Do you know correct type for SQLServer CE? Is it supported at all? I could not find any info about it.
I have also tried: SQL CE, SQLSERVER.CE, Microsoft.SQLSERVER.CE.OLEDB.3.5, Microsoft.SQLSERVER.MOBILE.OLEDB.3.0 etc. - Same error...
I think the stumbling block here is that the trick you are trying to use requires an ODBC connection to the SQL Server and as far as I know there is no ODBC driver for SQL Server Compact. I'm pretty sure that the syntax [ODBC;Driver=...] in Access has no OLEDB equivalent, so the trick won't work with SQL Server Compact. (As you discovered, it does work with "real" SQL Server because ODBC connections are supported for that platform.)
I was curious to see what I could accomplish in C# using an OLEDB connection to the SQL Server Compact database (which is supported, as #MrZak pointed out in his comment). I came up with the following. It pulls the SQL table into a DataTable, sets the status of each row to "Added", and then updates (inserts into) the corresponding table in Access.
string myConnectionStringMDB =
"Provider=Microsoft.ACE.OLEDB.12.0;" +
#"Data Source=C:\Users\Gord\Desktop\fromCE.mdb;";
string myConnectionStringSQL =
"Provider=Microsoft.SQLSERVER.CE.OLEDB.3.5;" +
#"Data Source=C:\Users\Public\test\myData.sdf;";
using (OleDbConnection conSQL = new OleDbConnection(),
conMDB = new OleDbConnection())
{
conSQL.ConnectionString = myConnectionStringSQL;
conSQL.Open();
conMDB.ConnectionString = myConnectionStringMDB;
conMDB.Open();
using (OleDbCommand cmdSQL = new OleDbCommand(),
cmdMDB = new OleDbCommand())
{
cmdSQL.CommandType = System.Data.CommandType.Text;
cmdSQL.Connection = conSQL;
cmdSQL.CommandText = "SELECT * FROM [Table1]";
var daSQL = new System.Data.OleDb.OleDbDataAdapter(cmdSQL);
var dt = new System.Data.DataTable();
daSQL.Fill(dt);
foreach (System.Data.DataRow dr in dt.Rows)
{
// change row status from "Unchanged" to "Added" so .Update below will insert them
dr.SetAdded();
}
cmdMDB.CommandType = System.Data.CommandType.Text;
cmdMDB.Connection = conMDB;
cmdMDB.CommandText = "SELECT * FROM [Table1]";
var daMDB = new System.Data.OleDb.OleDbDataAdapter(cmdMDB);
var cbuilderMDB = new OleDbCommandBuilder(daMDB);
cbuilderMDB.QuotePrefix = "[";
cbuilderMDB.QuoteSuffix = "]";
daMDB.Update(dt);
}
conSQL.Close();
conMDB.Close();
}
I'm still new to this, but "private void" from what I understand cant be imported or exported. Its only readable in that class or as a executable.

Showing information about databases in ado.net

How can I see all databases in curent connection using ado.net? And then see all tables in each database.
it gets all database
it gets all tables from database(this link was deleted now use this one. but change code little)
ADO.Net : Get table definition from SQL server tables
you can iterate over database and get all tables
To list all databases you need to specify connection string without initial database. Then you can execute "sp_databases" stored procedure.
To list all tables in database you need to query INFORMATION_SCHEMA.Tables.
SAMPLES
To get databases:
System.Data.SqlClient.SqlConnection SqlCon = new System.Data.SqlClient.SqlConnection("server=192.168.0.1;uid=sa;pwd=1234");
SqlCon.Open();
System.Data.SqlClient.SqlCommand SqlCom = new System.Data.SqlClient.SqlCommand();
SqlCom.Connection = SqlCon;
SqlCom.CommandType = CommandType.StoredProcedure;
SqlCom.CommandText = "sp_databases";
System.Data.SqlClient.SqlDataReader SqlDR;
SqlDR = SqlCom.ExecuteReader();
while(SqlDR.Read())
{
Console.WriteLine(SqlDR.GetString(0));
}
To get tables:
string connectionString = "...";
DataTable tables = new DataTable("Tables");
using (SqlConnection connection =
new SqlConnection(connectionString))
{
SqlCommand command = connection.CreateCommand();
command.CommandText = "select table_name as Name from
INFORMATION_SCHEMA.Tables where TABLE_TYPE =
'BASE TABLE'";
connection.Open();
tables.Load(command.ExecuteReader(
CommandBehavior.CloseConnection));
}
In visual Studio 2010
Select View => Server Explorer
Then write server name, if you use SQL Server Authentication, select it, write your user name and password, select or enter a database name => OK
In the Server Explorer under the Data Connections you will see your database and tables.

DataSet help in C#

I connected an sql database in c# and now trying to put the contents into a dataset. How will I be able to do that?
My code is:
string constr = "Data Source=ECEE;Initial Catalog=Internet_Bankaciligi;User ID=sa";
SqlConnection conn = new SqlConnection(constr);
SqlDataAdapter mySqlDataAdapter = new SqlDataAdapter("Select * from Internet_Bankaciligi", conn);
DataSet myDataSet = new DataSet();
DataRow myDataRow;
SqlCommandBuilder mySqlCommandBuilder = new SqlCommandBuilder(mySqlDataAdapter);
mySqlDataAdapter.MissingSchemaAction = MissingSchemaAction.AddWithKey;
mySqlDataAdapter.Fill(myDataSet,"Internet_Bankaciligi");
myDataRow = myDataSet.Tables["IB_Account"].NewRow();
myDataRow["Account_ID"] = "NewID";
myDataRow["Branch_ID"] = "New Branch";
myDataRow["Amount"] = "New Amount";
myDataSet.Tables["Customers"].Rows.Add(myDataRow);
the line: "mySqlDataAdapter.Fill(myDataSet,"Internet_Bankaciligi");" gives an error as 'Invalid object name 'Internet_Bankaciligi'.' but Internet_Bankaciligi is my database name.
Also if i use:
SqlCommand selectCMD = new SqlCommand("select (*) from IB_Account", conn);
SqlDataAdapter myAdapter = new SqlDataAdapter();
myAdapter.SelectCommand = selectCMD;
myAdapter.Fill(myDataSet);
then: "SqlCommand selectCMD = new SqlCommand("select (*) from IB_Account", conn);" gives an error saying invalid syntax. How will I get it correct?
If "Internet_Bankaciligi" is your actual database name, then you can't execute a SQL command directly against it. You have to change your SQL to select from a table or a view.
Your second example doesn't work because "SELECT (*)" is not valid syntax. It should be "SELECT * FROM IB_Account"... no parentheses.
I checked this statement in Sql Server 2008:
Select (*) from <table>
It doesn't work. I never seen this syntax, not in sqlserver 2005, nor Oracle nor sqlite.
try this one:
Select * from <table>
Edit: If I were you I will try using strongly typed datasets, or even Entity Framework which both are more advance and easier to work with. Google them.

Categories

Resources