how to use oracle dbms_utility in c# - c#

I want to use ORACLE DBMS feature in my C# application to compile all the invalid objects but I received below error. would you please help me how I can run below script in C#:
"exec dbms_utility.compile_schema('"+schema+"');";
my function :
internal void compileAllInvalideObject(string userId, string password, string schema)
{
//OracleConnection con = new OracleConnection();
string connectionString = "provider=MSDAORA;data source="+userId+";user id="+userId+";password="+password;
OleDbConnection myOleDbConnection = new OleDbConnection(connectionString);
OleDbCommand myOleDbCommand = myOleDbConnection.CreateCommand();
myOleDbCommand.CommandText = "exec dbms_utility.compile_schema('"+schema+"');";
myOleDbConnection.Open();
myOleDbCommand.ExecuteNonQuery();
myOleDbConnection.Close();
}
error:
ORA-00900: invalid SQL statement
I am using oracle 9i.

Actually dbms_utility.compile_schema act same as store procedure so we can not call it in same way which we run a query, we need to write program in such way we call a store procedure.
OracleConnection con = new OracleConnection();
//using connection string attributes to connect to Oracle Database
con.ConnectionString = "User Id="+userId+";Password="+password+";Data Source="+schema;
OracleCommand ocb = new OracleCommand("dbms_utility.compile_schema", con);
ocb.CommandType = CommandType.StoredProcedure;
ocb.Parameters.Add(new OracleParameter("#schema", userId));
con.Open();
ocb.ExecuteNonQuery();
Console.WriteLine("Connected to Oracle" + con.ServerVersion);
// Close and Dispose OracleConnection object
con.Close();
con.Dispose();
Console.WriteLine("Disconnected");

Related

C# SQL Connection not found

How can I connect a SQL database in C#?
My code:
const string connectionString = "Data Source=127.0.0.1;User ID=root;Database=MyDatabase;Password=MyPassword";
var conn = new SqlConnection(connectionString);
conn.Open();
conn.Close();
I get: Error: 40 - could not open a connection to sql server. I tried also in Python and it worked well:
cnx = mysql.connector.connect(user='root', password='MyPassword', host='127.0.0.1', database='MyDatabase')
cursor = cnx.cursor()
What am I missing in C#?
Please use MySqlConnection for MySql DB.
const string connectionString = "Data Source=127.0.0.1;User ID=root;Database=MyDatabase;Password=MyPassword";
MySqlConnection conn = new MySqlConnection(connectionString );
conn.Open();
string sqlcommand = "SELECT Query";
MySqlCommand cmd = new MySqlCommand(sqlcommand , conn);
please follow this example
using MySql.Data.MySqlClient;
var connectionString = "server=serveradress;database=dbName;user id=sqluser;password=abc;";
using (var connection = new MySqlConnection(connectionString))
{
connection.Open();
using var command = new MySqlCommand("SELECT COUNT(*) FROM tableName ", connection);
var Count = command.ExecuteScalar();
Console.WriteLine($"There are {Count } movies");
}
server adress in general is 127.0.0.1 ,if you are working locally
here the source page :
example
and also consider reading this page here docs

Oracle connection getting time out

I have an application which query database at a specific time of day and then it idle for next 3-4 hours and then again it queries database for some data but it is being executed only once and at the second attempt it is throwing an error.
using (OracleConnection connection = new OracleConnection())
{
connection.ConnectionString = connectionString;
connection.Open();
OracleCommand command = connection.CreateCommand();
string sql = _query;
command.CommandText = sql;
OracleDataAdapter oAdapter = new OracleDataAdapter(sql, connection);
oAdapter.Fill(myDataSet);
connection.Close();
return myDataSet;
}
The Error is being thrown at:
oAdapter.Fill(myDataSet);
And error stats as ORA-03113: end-of-file on communication channel
To my understanding connection should be disposed after one call and it should create another connection on each request. I have checked that the connection to the server is available and listening, no network issues while this error is occurring.
I got it, For any one else looking for answer is that I was calling return myDataSet; inside the using statement first i didn't notice it but as OracleConnection is being inherited from IDisposable and i was returning dataset inside using statement so it was never getting disposed off properly. so i just changed this from
using (OracleConnection connection = new OracleConnection())
{
connection.ConnectionString = connectionString;
connection.Open();
OracleCommand command = connection.CreateCommand();
string sql = _query;
command.CommandText = sql;
OracleDataAdapter oAdapter = new OracleDataAdapter(sql, connection);
oAdapter.Fill(myDataSet);
connection.Close();
return myDataSet;}
to
using (OracleConnection connection = new OracleConnection()){
connection.ConnectionString = connectionString;
connection.Open();
OracleCommand command = connection.CreateCommand();
string sql = _query;
command.CommandText = sql;
OracleDataAdapter oAdapter = new OracleDataAdapter(sql, connection);
oAdapter.Fill(myDataSet);
connection.Close(); }
return myDataSet;

Replacement for SqlConnection and SqlCommand

I have been writing a lot of open and close connection to a Microsoft SQL Server database. I'm not sure whether it is the latest technique available for .NET. Is there any latest .NET function that I'm missing?
Example code:
protected string InjectUpdateToProductDBString(string Command, TextBox Data, string TBColumn)
{
string connectionString = System.Configuration.ConfigurationManager.ConnectionStrings["AuthenticationDBConnectionString"].ConnectionString;
SqlConnection con = new SqlConnection(connectionString);
con.Open();
SqlCommand cmd = new SqlCommand(command, con);
cmd.Parameters.AddWithValue("#" + TBColumn, Data.Text.ToString());
cmd.ExecuteNonQuery();
con.Close();
return "Data successfully updated";
}
Is there any replacement for this fussy code technique? Just a discussion to improve my code technique.
There are other ways to write it and other tools you could use (like Entity Framework).
However, I recommend that you create a static function (or several) for your data access calls.
protected DataTable ExecuteSqlDataReader(string connection, string sqlQuery, SqlParameter[] cmdParams)
{
MySqlConnection con = new MySqlConnection(connection);
MySqlCommand cmd = new MySqlCommand(sqlQuery, con);
cmd.Parameters = cmdParams;
MySqlDataAdapter sda = new MySqlDataAdapter(cmd);
DataTable dt = new DataTable();
sda.Fill(dt);
sda.Command.Close();
return dt;
}
Create methods for Getting a dataTable, One value, ExecuteNonQuery, and even break it further down by abstracting out the SqlCommand creation to it's own method.
In any project, this code should be written only a few times.
Make sure that you enclose your SqlConnection in using statement. It will ensure the connection is closed even if there is an exception. Also, enclose your SqlCommand object in using statement, that will ensure disposal of unmanaged resources.
In your current code snippet if there is an exception at cmd.ExecuteNonQuery(); then your line con.Close would not execute, leaving the connection open.
So your method could be like:
protected string InjectUpdateToProductDBString(string Command, TextBox Data, string TBColumn)
{
string connectionString = System.Configuration.ConfigurationManager.ConnectionStrings["AuthenticationDBConnectionString"].ConnectionString;
using (SqlConnection con = new SqlConnection(connectionString))
{
con.Open();
using (SqlCommand cmd = new SqlCommand(command, con))
{
cmd.Parameters.AddWithValue("#" + TBColumn, Data.Text.ToString());
cmd.ExecuteNonQuery();
}
}
return "Data successfully updated";
}
Later you can return a DataTable or List<T> for your returned rows from the query.
If you want to move away from ADO.Net, then you can look into Object-Relation Mapping (ORM), which would provide you objects based on your database and easier way to manage your code base. Entity framework is one of them. You may see https://stackoverflow.com/questions/132676/which-orm-for-net-would-you-recommend
private SqlConnection GetConnection()
{
var con = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["AuthenticationDBConnectionString"].ConnectionString);
con.Open();
return con;
}
protected string InjectUpdateToProductDBString(string Command, TextBox Data, string TBColumn)
{
using (var con = GetConnection())
{
using (var cmd = con.CreateCommand())
{
cmd.Parameters.AddWithValue("#" + TBColumn, Data.Text);
cmd.ExecuteNonQuery();
return "Data Succesfully Updated";
}
}
}

insert in sql using c#

this code is successfully inserting a new value in a SQL db, but only when I insert constant values.
I need help where it says **(?)** in the code below, where I want to insert new values without specifying constants in the code.
What I mean is, I want to be able to type any random value in output window and it gets inserted into the SQL db.
private void InsertInfo()
{
String strConnection = "Data Source=HP\\SQLEXPRESS;database=MK;Integrated Security=true";
SqlConnection con = new SqlConnection(strConnection);
string connetionString = null;
SqlConnection connection ;
SqlDataAdapter adapter = new SqlDataAdapter();
connetionString = #"Data Source=HP\SQLEXPRESS;database=MK;Integrated Security=true";
connection = new SqlConnection(connetionString);
string sql = "insert into record (name,marks) **values( ?))";**
try
{
connection.Open();
adapter.InsertCommand = new SqlCommand(sql, connection);
adapter.InsertCommand.ExecuteNonQuery();
MessageBox.Show ("Row inserted !! ");
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
private void insert_Click(object sender, EventArgs e)
{
InsertInfo();
}
There is no need to use an adapter here; that is not helping you. Just:
var name = ...
var marks = ...
using(var conn = new SqlConnection(connectionString))
using(var cmd = conn.CreateCommand()) {
cmd.CommandText = "insert into record (name, marks) values (#name, #marks)";
cmd.Parameters.AddWithValue("name", name);
cmd.Parameters.AddWithValue("marks", marks);
conn.Open();
cmd.ExecuteNonQuery();
}
or with a tool like "dapper":
var name = ...
var marks = ...
using(var conn = new SqlConnection(connectionString)) {
conn.Open();
conn.Execute("insert into record (name, marks) values (#name, #marks)",
new {name, marks});
}
Those '?' are termed as parameters. From what I understand, you are wanting to use a parametrized query for your insert which is a good approach as they save you from chance of a SQL injection. The '?' sing in your query is used when you are using an
OLEDBConnection & Command object.
Normally, you would use '#' symbol to specify a parameter in your query. There is no need for an adapter. You just
//Bind parameters
// Open your Connection
// Execute your query
// Close connection
// return result
Parametrized queries 4 Guys from Rolla
MSDN: How to Protect from SQL injection in ASP.NET

Using a existing connection in a Script Component (SSIS)

I have am OLEDB Connection configured in the connection managers and I want to use it in a SCRIPT. The script needs to call a stored proc and then create buffer rows. I have added the connection to the connections available to the script and this is my code.
Boolean fireagain = true;
SqlConnection conn = new SqlConnection();
conn = (SqlConnection)(Connections.Connection
.AcquireConnection(null) as SqlConnection);
SqlCommand cmd = new SqlCommand();
conn.Open();
ComponentMetaData.FireInformation(
0, "Script", "Connection Open", string.Empty, 0, ref fireagain);
cmd.Connection = conn;
cmd.CommandText = "up_FullTextParser_select" ;
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("Phrase", DbType.String).Value = Row.Keywords;
cmd.Parameters.AddWithValue("SpecialTerm", DbType.String).Value = "Exact match";
cmd.Parameters.AddWithValue("StopListId", DbType.Int32).Value = 0;
SqlDataReader rdr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
while (rdr.Read())
{
TermsBuffer.AddRow();
TermsBuffer.Term = rdr[0].ToString();
}
conn.Close();
Anyway, it seems to fail on the AcquireConnection. Am I converting this wrong? Should I be using a different way to using the connections defined outside the script?.
You cannot cast an OLEDB connection to SqlConnection object. You must use the OleDbConnection object. See the example - http://blogs.msdn.com/b/mattm/archive/2008/08/22/accessing-oledb-connection-managers-in-a-script.aspx
This MSDN example implies that you using AcquireConnection incorrectly.
You need to use a managed connection provider.
If you insist on using an OLEDB connection, you cannot use AcquireConnection but you can extract the connection string and then use it to create an OLEDB connection:
string connstr = Dts.Connections["my_OLEDB_connection"].ConnectionString;
System.Data.OleDb.OleDbConnection objConn = new System.Data.OleDb.OleDbConnection(connstr);
This may not work if the connection string is created via an expression of some sort.
IDTSConnectionManager100 connMgr = this.Connections.ADONetAppStaging ; //this we need to give name in connection manager in script component
SqlConnection myADONETConnection = new SqlConnection();
myADONETConnection = (SqlConnection)(connMgr.AcquireConnection(null));
//Read data from table or view to data table
string query = "Select top 10 * From ##AP_Stagging_Temp_ExportWODuplicates Order by 1,2,3 asc ";
// string query = "Select * From ##AP_Stagging_Temp_For_JLL_ExportWODuplicates order by 1,2,3 asc ";
SqlDataAdapter adapter = new SqlDataAdapter(query, myADONETConnection);
datatable dtExcelData = new datatable();
adapter.Fill(dtExcelData);
myADONETConnection.Close();

Categories

Resources