public static void connect()
{
try
{
string connectionStringStaging = #"Data Source=<server_name>;Catalog=<catalog_name>;User ID=<user_name>;Password=<my_password>";
string commandText = #"SELECT NON EMPTY { [Measures].[# Opptys moved to Committed] } ON COLUMNS FROM [Model]
CELL PROPERTIES VALUE, BACK_COLOR, FORE_COLOR, FORMATTED_VALUE, FORMAT_STRING, FONT_NAME, FONT_SIZE, FONT_FLAGS";
AdomdConnection connection = new AdomdConnection(connectionStringStaging);
connection.Open();
AdomdCommand cmd = new AdomdCommand(commandText);
cmd.Connection = connection;
using (var reader = cmd.ExecuteReader())
{
while (reader.Read())
{
Console.WriteLine(reader[0]);
}
}
}
catch (AdomdConnectionException ex)
{
Console.WriteLine("Error : " + ex.ToString());
}
}
I am using the above code to connect to server and then I am further running MDX queries using this.The problem is the error I am getting - "The connection string is not valid" at line
connection.open();
Are the settings name incorrect which I am using in my connection string?Can someone help me figure out what is wrong in my connection string ?
The stack trace is as follows:
Please consult the following documentation from Microsoft: https://msdn.microsoft.com/en-us/library/microsoft.analysisservices.adomdclient.adomdconnection.connectionstring.aspx
You can also find some examples of connection strings here: https://www.connectionstrings.com/adomd-net/
Hope this will help you sort the problem.
I found my answer here. The unofficial package worked just fine . So I installed the reference Unofficial.Microsoft.AnalysisServices.AdomdClient and so the problem was not in the connection string but in the package.
Related
I'm creating a web API using .Net Core and the Oracle.ManagedDataAccess.Core plugin that accesses an Oracle database to retrieve a Blob field and return it as a byte array. I created a function (getBlobfromDB) that gets the Oracle connection string from an encrypted field on a SQL database, connects and uses an OraleDataReader to retrieve and return the Blob field. But when the OraleDataReader tries to Read the record, I'm getting this exception: "Invalid operation on a closed object".
When you search for this issue, the most relevant answer is this post
However, I'm 100% percent sure that user on the conn string has access since that is the schema owner, and I also tried adding the schema owner to the Select query (SELECT FIELD FROM SCHEMA_OWNER.TABLE WHERE ID = "") getting the same error
So I tried two other things, getting a different VARCHAR field from another table on the same database, still getting the same error; and trying on a different Oracle database and I was able to successfully retrieve the data. I noticed that the Oracle versions on the servers are different, 12.2 for the working one and 11.2 for the non-working, this may be the reason? I don't know what else I can do or try, I'll appreciate any help/advice that you can give me
This is the simplified function
private OracleBlob getBlobfromDB(string sSystem, string sID)
{
string sSQL = String.Empty;
string connString = String.Empty;
OracleConnection oConn = new OracleConnection();
if (string.IsNullOrWhiteSpace(sID) || string.IsNullOrWhiteSpace(sSystem) )
{
return null;
}
sSQL = "SELECT BLOB_FIELD FROM TABLE WHERE ID = " + sID;
connString = getConnectionString(sSystem);
try
{
using (oConn = new OracleConnection(connString))
{
oConn.Open();
OracleCommand oCom = new OracleCommand(sSQL, oConn);
OracleDataReader oDr = oCom.ExecuteReader();
if (oDr.HasRows)
{
//I'm able to reach to this point before getting the exception
oDr.Read();
OracleBlob blob = oDr.GetOracleBlob(0);
// Clean up
oDr.Close();
oDr.Dispose();
oCom.Dispose();
return blob;
}
else
{
// Clean up
oDr.Close();
oDr.Dispose();
oCom.Dispose();
return null;
}
}
}
catch (Exception x)
{
return null;
}
finally
{
oConn.Close();
}
}
With the Oracle.ManagedDataAccess dependency you should not Close() the connection and do not use the using clause. It seems that the dependency itself closes the connection at will.
Remove: using(){} keyword and oConn.Close() from your code.
I am very new in C# and now try to find online resource to connect VS C# to mySQL database at server 'localhost', with userid 'root', and password '****', the databasename is 'dlht'.
1.I copied a line of code from youtube and it works:
this.stockTableAdapter.Fill(this.blhsDataSet.stock);
Can anyone explain to me what exactly this is doing? There is no place to put server, password, userid etc... How can it work?
I tried to use the online tutorials to connect to mySQL database
ZetCode C#Tutorial
string cs = #"server=localhost;userid=root;
password=****;database=dlht";
MySqlConnection conn = null;
try
{
conn = new MySqlConnection(cs);
conn.Open();
Console.WriteLine("MySQL version : {0}", conn.ServerVersion);
} catch (MySqlException ex)
{
Console.WriteLine("Error: {0}", ex.ToString());
} finally
{
if (conn != null)
{
conn.Close();
}
}
I run this code at Form1.cs at VS C#. It is always stuck at :
conn = new MySqlConnection(cs);
Why? Thank you so much!
It seems that the proper way to connect to MySql database is this
Server=myServerAddress;Database=myDataBase;Uid=myUsername;Pwd=myPassword;
I've written a function to perform MySQL statements. In this function I give in a statement and get back the MySqlDataReader, but the problem is my function do not close the connection. After a short while of using the Programm, it crashs because the new connection can't be open. This is the error i got by trying open the new connection:
error connecting: Timeout expired. The timeout period elapsed prior
to obtaining a connection from the pool. This may have occurred
because all pooled connections were in use and max pool size was
reached.
My code look like this:
MySQL Class:
class mySql
{
string cs = "server=123.123.123.123;" +
"uid=abcabc;" +
"pwd=123456;" +
"database=overflow_test;";
private MySqlConnection conn_f() // create a Connection
{
MySql.Data.MySqlClient.MySqlConnection conn;
conn = new MySql.Data.MySqlClient.MySqlConnection();
conn.ConnectionString = cs;
try
{
conn.Open();
return conn;
}
catch
{
return null;
}
}
public MySqlDataReader CMD_f(string comand) //execute SQL Command
{
MySql.Data.MySqlClient.MySqlCommand cmd;
cmd = new MySql.Data.MySqlClient.MySqlCommand();
MySqlConnection conn = conn_f();
cmd.Connection = conn;
cmd.CommandText = comand;
cmd.Prepare();
rdr = cmd.ExecuteReader();
return rdr;
}
}
and an example how i use it Main Class
class main{
mySql DB = new mySql();
public void main(){
MySqlDataReader rdr = DB.CMD_f("SELECT * FROM tbl_kategorie");
int i = 0;
while (rdr.Read())
{
string str = rdr.GetString(1);
Console.WriteLine(str);
}
}
Has someone an Idea to solve the Problem.
Sincere regards LFS96 (Fabian Harmsen)
The main problem is the inbalance in the code. The CMD_f method creates a connection, but doesn't take responsibility for it. You should rather make the method that creates the connection public, so that you can take responsibility for it in the code that can close it.
That's a bigger change, so first let's look at a smaller change to fix the code.
The data reader should expose the data connection as the Connection property. I don't see that in the documentation, so it's possible that it doesn't, but the data readers in the .NET framework does.
If the property is exposed, then you can make a quick fix to make the code work with minimal change:
MySqlDataReader rdr = DB.CMD_f("SELECT * FROM tbl_kategorie");
int i = 0;
while (rdr.Read())
{
string str = rdr.GetString(1);
Console.WriteLine(str);
}
rdr.Close();
rdr.Connection.Close();
If you make the conn_f method public and don't call it in the CMD_f method, you can write much more robust code, that never leaves a connection or data reader hanging even if there is an error. That's a bigger change in the code, but definitely worth the effort when you have time to implement and test it. Using a using block to make sure that the objects are always disposed correctly makes the code much more resilient:
using (MySqlConnection conn = DB.conn_f()) {
using (MySqlDataReader rdr = DB.CMD_f(conn, "SELECT * FROM tbl_kategorie")) {
int i = 0;
while (rdr.Read()) {
string str = rdr.GetString(1);
Console.WriteLine(str);
}
}
}
Side note: Identifiers in C# tend to be descriptive. I suggest names like DB.CreateConnection and DB.ExecuteReader rather than DB.conn_f and DB.CMD_f.
I am new to net developing and have managed to work my way through a lot of questions I have had just by looking through the forums.
It appears that the issue that I am having is something that a number of others have had I have found that they are all different and just haven't for the life of me been able to work through it.
I am trying to insert player registration details into database but when I try to invoke the wcf server it am met with the exception type on my conn.Open():
An exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll but was not handled in user code.
In addition I am using the build it sql server and the connection string used is one from properties on the database.
I am not too sure how to proceed.
public string playerRegistration(playerDetails playerInfo)
{
string Message;
using (SqlConnection conn = new SqlConnection("Data Source=(LocalDB)\v11.0;AttachDbFilename=c:\\Users\\Daniel\\documents\\visual studio 2013\\Projects\\Prac4\\WebApplication1\\App_Data\\ADODatabase.mdf;Integrated Security=True"))
{
conn.Open();
using (var cmd = new SqlCommand("INSERT into Player(pid, pfname, plname, pphone, paddress, pdob) VALUES (#pid, #pfname, #plname, #pphone, #paddress, #pdob)", conn))
{
cmd.Parameters.AddWithValue("#pid", playerInfo.Pid);
cmd.Parameters.AddWithValue("#pfname", playerInfo.Pfname);
cmd.Parameters.AddWithValue("#plname", playerInfo.Plname);
cmd.Parameters.AddWithValue("#pphone", playerInfo.Pphone);
cmd.Parameters.AddWithValue("#paddress", playerInfo.Paddress);
cmd.Parameters.AddWithValue("#pdob", playerInfo.Pdob);
int result = cmd.ExecuteNonQuery();
if (result == 1)
{
Message = " Details inserted successfully";
}
else
{
Message = " Details not inserted successfully";
}
conn.Close();
return Message;
}
}
}
Make sure to use #".." (a verbatim string literal) with connection strings to avoid simple escaping mistakes.
The code shown with "..\v.." contains a vertical tab escape which produces an invalid connection string. There is no compiler error because the string literal is syntactically valid although the resulting string is incorrect.
Recommended fix with a verbatim string literal and elimination of double slashes:
#"Data Source=(LocalDB)\v11.0;AttachDbFilename=c:\Users\Daniel.."
Alternative fix (note the \\v):
"Data Source=(LocalDB)\\v11.0;AttachDbFilename=c:\\Users\\Daniel.."
The problem is in your connection string
"Data Source=(LocalDB)\v11.0;AttachDbFilename=c:\\Users\\Daniel\\documents\\visual studio 2013\\Projects\\Prac4\\WebApplication1\\App_Data\\ADODatabase.mdf;Integrated Security=True"
Search the internet to find the required format for SQL Server. You do not need an MDF file name, here's a helpful link:
https://www.connectionstrings.com/sql-server/
I've searching for this and I thought I found the answer on here. this is the code I found to run a sql script through c#:
using System.Data.SqlClient;
using System.IO;
using Microsoft.SqlServer.Management.Common;
using Microsoft.SqlServer.Management.Smo;
namespace SeleniumTest2
{
class CreateSchema
{
public void Schema_Create()
{
string sqlConnectionString = "connection string here";
FileInfo file = new FileInfo(#"filepath to script.sql");
string script = file.OpenText().ReadToEnd();
SqlConnection conn = new SqlConnection(sqlConnectionString);
Server server = new Server(new ServerConnection(conn));
//DOESNTLIKE
server.ConnectionContext.ExecuteNonQuery(script);
file.OpenText().Close();
conn.Close();
}
}
}
But I keep getting the following error:
An unhandled exception of type 'Microsoft.SqlServer.Management.Common.ExecutionFailureException' occurred in Microsoft.SqlServer.ConnectionInfo.dll
Additional information: An exception occurred while executing a Transact-SQL statement or batch.
Can anyone tell me how to overcome this error?
THANKS!!
This happened to me a couple times. After debugging, there were some errors in my script file itself. The following worked for me:
Try running your script file directly using SQL Management Studio. This can pinpoint errors in your script itself.
Break down the SQL script into smaller files. For some reason this worked for me. Split the file into smaller scripts accordingly. For my particular database creation script, I separated it into a create tables script, a populate tables script, and an add primary and foreign keys script.
My code:
/// <summary>
/// Process SQL script with "GO" statements
/// </summary>
/// <param name="script"></param>
public static void ProcessSQLScriptFile(string script)
{
try
{
SqlConnection con = new SqlConnection(Properties.Settings.Default.SQLConDefault); // your connection string
con.Open();
Server server = new Server(new ServerConnection(con));
server.ConnectionContext.ExecuteNonQuery(script);
con.Close();
}
catch (SqlException e)
{
Console.WriteLine("SQL Exception: " + e.Message);
}
catch (Exception e)
{
Console.WriteLine("Exception: " + e.Message);
}
}
Hope this helps.
You may try this method to execute sql (from msdn):
private static void ExecuteCommand(string queryString,
string connectionString)
{
using (SqlConnection connection = new SqlConnection(
connectionString))
{
SqlCommand command = new SqlCommand(queryString, connection);
command.Connection.Open();
command.ExecuteNonQuery();
}
}
If you will get an error, check exception details, check if your connection string is valid.
I had this exact same issue. What fixed it for me was to find out the actual error:
public void Schema_Create()
{
string sqlConnectionString = "connection string here";
FileInfo file = new FileInfo(#"filepath to script.sql");
string script = file.OpenText().ReadToEnd();
SqlConnection conn = new SqlConnection(sqlConnectionString);
Server server = new Server(new ServerConnection(conn));
try
{
server.ConnectionContext.ExecuteNonQuery(script);
}
catch (Exception ex)
{
Console.WriteLine("Error: " + ex.InnerException.Message);
}
file.OpenText().Close();
conn.Close();
}
My issue presented itself in the ex.InnerException.Message, which in my case happened to be that my script was attempting to write a column that already existed on the table (column names must be unique for a given table).
Change the database path to another drive
Because in c drive or in windows drive you don't have permission to create data base
If change the path , your solution is work successful.