I'm using the following code to execute a query in C#:
// Create Connection String
AdomdConnection testConnection = new AdomdConnection("Data Source=*****;User ID=******;Provider=MSOLAP.6;Persist Security Info=True;Impersonation Level=Impersonate;Password=******");
// Test Open
testConnection.Open();
// Make Query
AdomdCommand cmd = new AdomdCommand(#"SELECT { [Measures].[Payment Amount] } ON COLUMNS,
{ [Charging Low Orgs].[Charging Division].[Charging Division] } ON ROWS
FROM [Payments]", testConnection);
AdomdDataReader dataReader = cmd.ExecuteReader();
// Close Connection
testConnection.Close();
And I keep getting this error on the cmd.ExecuteReader() call:
{"XML for Analysis parser: The CurrentCatalog XML/A property was not specified."}
The only literature that I could find that was relavent to this was that the query isn't resolving because impersonation wasn't set, but I specified that in the connection string.
Another article which I don't think is related, said to enable BAM on Excel, but I don't have that option in Excel, and I fail to see how that would make a difference for a web service.
Please help!
The following example includes a catalog parameter in the connection string:
static void Main(string[] args)
{
AdomdConnection conn = new AdomdConnection(
"Data Source=localhost;Catalog=Adventure Works DW Standard Edition");
conn.Open( );
string commandText = "SELECT {[Measures].[Sales Amount], " +
"[Measures].[Gross Profit Margin]} ON COLUMNS, " +
"{[Product].[Product Model Categories].[Category]} ON ROWS " +
"FROM [Adventure Works] " +
"WHERE ([Sales Territory Country].[United States])";
AdomdCommand cmd = new AdomdCommand(commandText, conn);
AdomdDataReader dr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
Related
I'm trying to update a CLOB column in my database with a long string containing the HTML contents of an email. There are 18,000 characters in the record I'm having an issue with.
The below code will work if I set the html variable to "short string". But if I try to run the code with the long 18,000 character HTML string, I get this error: "Oracle.DataAccess.Client.OracleException ORA-22922: nonexistent LOB value ORA-02063: preceding line from ((servername))"
public static void UpdateHtmlClob(string html, string taxId,string un, string pw)
{
using (OracleConnection conn = new OracleConnection())
{
try
{
conn.ConnectionString = "User Id=" + un + ";Password=" + pw + ";Data Source=server.com;";
conn.Open();
OracleCommand cmd = new OracleCommand();
string indata = html;
cmd.CommandText = "UPDATE table1 SET HTML_BODY = :clobparam";
OracleParameter clobparam = new OracleParameter("clobparam", OracleDbType.Clob, indata.Length);
clobparam.Direction = ParameterDirection.Input;
clobparam.Value = indata;
cmd.Parameters.Add(clobparam);
cmd.Connection = conn;
cmd.ExecuteNonQuery();
conn.Close();
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
conn.Close();
}
}
}
Before you edited your code to reflect my answer, there were two problems with your code that I saw.
Firstly, you need to use a colon in your command text to tell Oracle that clobparam is a bind variable, not a column name:
cmd.CommandText = "UPDATE table1 SET HTML_BODY = :clobparam";
Secondly, you were not setting the database connection anywhere on the command. Which connection should the command be using? In your situation you have only one connection but more generally it may be possible to have more than one connection open. Add the line
cmd.Connection = connection;
or alternatively create the command using
OracleCommand cmd = connection.CreateCommand();
Of course, it would be nice if Oracle.DataAccess returned an error message that gave you the slightest hint that this was what you were doing wrong.
Anyway, now that you've edited your question to include the critical detail ORA-02063: preceding line from ((servername)), which tells us that you are using a database link, all I can really do is echo what I wrote in the comment: connect direct to the remote database to transfer LOB data, don't use a database link.
Hi I am developing an application to retrieve data from one system to another remote system.
To do this I am firstly setting the connection string of the application by below screen.
When I chose the SQL Server from first dropdownlist I need that the available DataSource name or database instance name like sa or anything by witch the database installed, should be come in second dropdownlist and again when I select DataSource available, database name should be prompt in 3rd dropdownlist.
I don't have any idea about this how can I do this. Currently I am doing this manually but it's time consuming and error prone.
How can we resolve it and also for MySql too.
You can get the database instance name using following code
SqlDataSourceEnumerator instance = SqlDataSourceEnumerator.Instance;
System.Data.DataTable table = instance.GetDataSources();
foreach (System.Data.DataRow row in table.Rows)
{
cboServerName.Items.Add(row["ServerName"]);
}
and for the databases in that server you can use this code
SqlConnection SqlCon = new SqlConnection("server=" + cboServerName.SelectedItem.ToString() + ";uid=" + txtUsername.Text + ";pwd=" + txtPassword.Text);
try
{
SqlCon.Open();
//if connection was successful,fetch the list of databases available in that server
SqlCommand SqlCom = new SqlCommand();
SqlCom.Connection = SqlCon;
SqlCom.CommandType = CommandType.StoredProcedure;
SqlCom.CommandText = "sp_databases"; //sp_databases procedure used to fetch list of available databases
SqlDataReader SqlDR;
SqlDR = SqlCom.ExecuteReader();
while (SqlDR.Read())
{
cboDatabase.Items.Add(SqlDR.GetString(0));
}
}
catch
{
MessageBox.Show("Connection Failed...Please check username and password","Error");
}
What I need to do is basically take the users name (which is already stored as a variable) and their score (which is also a variable) and store it in my database when they press 'submit'. Here is the code I have for the button click.
private void btnSubmitScore_Click(object sender, EventArgs e)
{
string connStr = "server=server; " +
"database=databasename; " +
"uid=username; " +
"pwd=password;";
MySqlConnection myConn = new MySqlConnection(connStr);
}
Obviously i have changed the login details etc. I have had a look around and have only managed to find confusing codes about how to display data from a database in a form (i will do this later), but for now, i need to know how to add sName and iTotalScore into the database. (Fields are called 'Name' and 'Score' in DB)
You are going to use a combination of SqlConnection, SqlCommand and their properties. the connection is essentially the stuff of your code. The command is a literal SQL statement, or a call to a stored procedure.
A common C# idiom is to form your code around the very first line as shown here:
using (SqlConnection myConnection = new SqlConnection()) {
string doThis = "select this, that from someTable where this is not null";
SqlCommand myCommand = new SqlCommand(dothis, myConnection);
try {
myCommand.Connection.Open();
myReader = myCommand.ExecuteReader(); //pretend "myReader" was declared earlier
} catch (Exception myEx) {
// left to your imagination, and googling.
}
finally {
myCommand.Connection.Close();
}
}
// do something with the results. Your's to google and figure out
The general outline is
Using a connection
instantiate and configure an SqlCommand
Use try/catch as shown.
The "using" block gives use behind the scenes cleanup/disposal of all those objects we don't need anymore when we're done; in particular the SqlConnection object.
You must learn more about these Sqlxxxxx classes, there's lots of ways to configure them to do what you want.
I am not familiar with the MySql connector, but the code should be something along the lines of:
private void Insert()
{
string connStr = "server=server; " +
"database=databasename; " +
"uid=username; " +
"pwd=password;";
string query = "INSERT INTO TableName('Name','Score) VALUES (#name, #score);";
using(MySqlConnection connection = new MySqlConnection(connStr))
{
MySqlCommand insertCommand = new MySqlCommand(connection,command);
insertCommand.Paramaters.AddWithValue("#name",sName);
insertCommand.Paramaters.AddWithValue("#score",iTotalScore);
connection.Open();
command.ExecuteNonQuery();
connection.Close();
}
}
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
My need is to write a code, which
creates a db
creates four tables
creates primary keys
creates foreign keys
and constraints like type int or boolean or string etc
Yes I know w3c shools has the sql codes, but the problem is I first need to detect if these things exists or not one by one.
And this is for me a great problem.
I tried to work with sql exceptions, but it does not provide way to categorize the exceptions --like databasethereexception--tablealreadythereEXCEPTION..
So please provide some coded examples or links for the above purpose,
note: yes I can google, but it is full full full of examples and codes, it gets too confusing, so hoping for straight professional examples please
Also a sample of the type of code i am working with
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data;
public partial class Making_DB : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
//check or make the db
MakeDB();
CheckDB();
}
public void CheckDB()
{
try
{
string Data_source = #"Data Source=A-63A9D4D7E7834\SECOND;";
string Initial_Catalog = #"Initial Catalog=master;";
string User = #"User ID=sa;";
string Password = #"Password=two";
string full_con = Data_source + Initial_Catalog + User + Password;
SqlConnection connection = new SqlConnection(full_con);
connection.Open();
SqlDataAdapter DBcreatingAdaptor = new SqlDataAdapter();
DataSet ds2 = new DataSet();
SqlCommand CheckDB = new SqlCommand("select * from sys.databases where name = 'my_db'", connection);
DBcreatingAdaptor.SelectCommand = CheckDB;
DBcreatingAdaptor.Fill(ds2);
GridView1.DataSource = ds2;
GridView1.DataBind(); // do not forget this//
Response.Write("<br />WORKING(shows zero if db not there) checking by gridview rows: " + GridView1.Rows.Count.ToString());
Response.Write("<br />NOT WORKING(keeps on showing one always!) checking by dataset tables: " + ds2.Tables.Count.ToString());
DBcreatingAdaptor.Dispose();
connection.Close();
//Inaccesible due to protection level. Why??
//SqlDataReader reader = new SqlDataReader(CheckDB, CommandBehavior.Default);
}//try
catch (Exception e)
{
Response.Write(" checking:: " + e.Message);
}//catch
}//check db
public void MakeDB()
{
try
{
string Data_source = #"Data Source=A-63A9D4D7E7834\SECOND;";
//string Initial_Catalog = #"Initial Catalog=replicate;";
string User = #"User ID=sa;";
string Password = #"Password=two";
string full_con = Data_source + User + Password;
SqlConnection connection = new SqlConnection(full_con);
connection.Open();
//SqlCommand numberofrecords = new SqlCommand("SELECT COUNT(*) FROM dbo.Table_1", connection);
SqlCommand CreateDB = new SqlCommand("CREATE DATABASE my_db", connection);
//DataSet ds2 = new DataSet();
SqlDataAdapter DBcreatingAdaptor = new SqlDataAdapter();
DBcreatingAdaptor.SelectCommand = CreateDB;
DBcreatingAdaptor.SelectCommand.ExecuteNonQuery();
//check for existance
//select * from sys.databases where name = 'my_db'
DataSet ds2 = new DataSet();
SqlCommand CheckDB = new SqlCommand(" select * from sys.databases where name = 'my_db'", connection);
DBcreatingAdaptor.SelectCommand = CheckDB;
//DBcreatingAdaptor.SelectCommand.ExecuteReader();
DBcreatingAdaptor.Fill(ds2);
GridView1.DataSource = ds2;
//if not make it
}//try
catch (Exception e)
{
Response.Write("<br /> createing db error: " + e.Message);
}//catch
}//make db
}
As I've already mentioned in my comment - I would NEVER write out directly to the Response stream from a function like this! Pass back a string with an error message or something - but do NOT write out to the stream or screen directly.
You should use the best practice of wrapping SqlConnection and SqlCommand into using(...){.....} blocks to make sure they get properly disposed. Also, populating a gridview from within this code is really bad - you're mixing database access (backend) code and UI frontend code - really really bad choice. Why can't you just pass back the data table and then bind it in the UI front end code to the grid??
public DataTable CheckDB()
{
DataTable result = new DataTable();
try
{
string connectionString =
string.Format("server={0};database={1};user id={2};pwd={3}"
"A-63A9D4D7E7834\SECOND", "master", "sa", "two");
string checkQuery = "SELECT * FROM sys.databases WHERE name = 'my_db'";
using(SqlConnection _con = new SqlConnection(connectionString))
using(SqlCommand _cmd = new SqlCommand(checkQuery, _con))
{
SqlDataAdapter DBcreatingAdaptor = new SqlDataAdapter(_cmd);
DBcreatingAdaptor.Fill(_result);
}
}//try
catch (SqlException e)
{
// you can inspect the SqlException.Errors collection and
// get **VERY** detailed description of what went wrong,
// including explicit SQL Server error codes which are
// unique to each error
}//catch
return result;
}//check db
Also - you're doing the MakeDB() method way too complicated - why a table adapter?? All you need is a SqlCommand to execute your SQL command - you already have a method that checks that a database exists.
public void MakeDB()
{
try
{
string connectionString =
string.Format("server={0};database={1};user id={2};pwd={3}"
"A-63A9D4D7E7834\SECOND", "master", "sa", "two");
string createDBQuery = "CREATE DATABASE my_db";
using(SqlConnection _con = new SqlConnection(connectionString))
using(SqlCommand _cmd = new SqlCommand(createDBQuery, _con))
{
_con.Open();
_cmd.ExecuteNonQuery();
_con.Close();
}
}//try
catch (SqlException e)
{
// check the detailed errors
// error.Number = 1801 : "database already exists" (choose another name)
// error.Number = 102: invalid syntax (probably invalid db name)
foreach (SqlError error in e.Errors)
{
string msg = string.Format("{0}/{1}: {2}", error.Number, error.Class, error.Message);
}
}//catch
}//make db
I am very sure of the cross-over between this and the other question - however, it sounds to me like you are approaching this from the wrong end.
I would write this as a TSQL script, making use of EXEC to avoid problems with the checker, for example:
USE [master]
if not exists ( ... database ...)
begin
print 'creating database...'
exec ('...create database...')
end
GO
USE [database]
if not exists( ... check schema tables for 1st thing ... )
begin
print 'Creating 1st thing...'
exec ('...create 1st thing...')
end
if not exists( ... check schema tables for 2nd thing ... )
begin
print 'Creating 2nd thing...'
exec ('...create 2nd thing...')
end
if not exists( ... check schema tables for 3rd thing ... )
begin
print 'Creating 3rd thing...'
exec ('...create 3rd thing...')
end
Then you can gradually extend this script as your schema changes, and all you need to do is re-run the script for it to update the database.
May be it is not directly you want, but for easy database creation & population from .Net review usage of wide migrate tool. My preference (Migrator.NET) but full review can be found there: http://flux88.com/blog/net-database-migration-tool-roundup/
I am using the following code do get all data records from a MS SQL database and I try to update every single record. The code is used in a WebService. The issue is, that the code runs fine if I have 1000 data records but now I have 20000 data records an the code first returned with an timeout. Then I set the cmd.CommandTimeout to zero to have no timeout. Now when I invoke the function in the IE WebSvc the IE window is still blank and still try to load something but nothing happens. Only 150 datarecords are updated.
Do you have any idea where the issue might be ? Is the code not the best, so what should I change ?
Thank you very much!
WorldSignia
MyCode:
private string AddNewOrgBez()
{
try
{
SqlConnection sqlconn = new SqlConnection(this.connectionString);
SqlCommand cmd;
SqlDataReader reader;
sqlconn.Open();
cmd = new SqlCommand("SELECT * FROM dbo.mydata", sqlconn);
cmd.CommandTimeout = 0;
reader = cmd.ExecuteReader();
while (reader.Read())
{
// Felder holen
string okuerzel = reader["O_KURZ"].ToString();
string bezeichnung = reader["O_BEZ"].ToString();
string[] lines = CreateNewOrgBez(bezeichnung);
string sqlcmd = "UPDATE dbo.mydata SET WEB_OBEZ1 = '" + lines[0] + "', WEB_OBEZ2 = '" + lines[1] + "', WEB_OBEZ3 = '" + lines[2] + "' WHERE O_KURZ = '" + okuerzel + "'";
SqlConnection sqlconn2 = new SqlConnection(this.connectionString);
sqlconn2.Open();
SqlCommand cmd2 = new SqlCommand(sqlcmd, sqlconn2);
cmd2.CommandTimeout = 0;
cmd2.ExecuteNonQuery();
sqlconn2.Close();
}
reader.Close();
sqlconn.Close();
return "OK";
}
catch (Exception ex)
{
return ex.Message;
}
}
You are leaking every SqlCommand here - I suggest you review your use of SqlClient classes to find the ones that are IDisposable and restructure your code to ensure they are always freed, using the using construct.
For example, this ensures Dispose gets called even if there is an exception in the bracketed code:
using (SqlCommand cmd2 = new SqlCommand(sqlcmd, sqlconn2))
{
cmd2.CommandTimeout = 0;
cmd2.ExecuteNonQuery();
}
Using a new SqlConnection for every UPDATE is expensive too, this should be done outside the loop. Redundant connection establishment is likely the explanation for your timeout.
Take note of #ck's comment that for efficiency this type of piecemeal client-side operation is not as good as doing the heavy lifting server-side. You should be able to get this code working better, but that does not mean it's the ideal/fastest solution.
I found the issue.
You need first to get all the data records, for example in a new DataTable. The structure I used does not work, because it reads data from the database and also updates the database. After changing it to a new structure it works.
You were using two different connections to read and to update, and one of them was blocking another. This is why when you read all your data first, it began to work.
I doubt if your running into OutOfMemoryException. Can you profile your application and check the memory usage?
Since you are just overwriting the variables in While loop, why don't you try taking them out of the loop.