No start database manager command was issued error - c#

I have a DB2 expresss in my machine and I am able to query from the database using command window (after following two commands):
set DB2INSTANCE=db2inst1
db2 connect to tims user
Now, when I try to connect to the database from a C# console application, I am getting following errors with different connection strings.
Attempt 1
string connectionString = #"Provider = IBMDADB2; Database = TIMS; Hostname = localhost; CurrentSchema=db2inst1; ";
SQL1032N No start database manager command was issued. SQLSTATE=57019
Attempt 2
string connectionString = #"Provider = IBMDADB2; Database = TIMS; CurrentSchema=db2inst1; ";
SQL1031N The database directory cannot be found on the indicated file system. SQLSTATE=58031
What should be the correct connection string for this scenario?
CODE
string connectionString = #"Provider = IBMDADB2; Database = TIMS; Hostname = localhost; CurrentSchema=db2inst1; ";
OleDbConnection myConnection = new OleDbConnection();
myConnection.ConnectionString = connectionString;
myConnection.Open();

Do you have multiple DB2 instances running on your machine? You can get a list of instances that exist by executing the db2ilist command.
If you have to execute the set DB2INSTANCE=db2inst1 statement when you open a DB2 Command Window in order to connect to the TIMS database with the db2 connect to TIMS command, then you need to ensure that the environment for your C# application is configured the same way.
You can do this in a number of ways:
by setting the DB2INSTANCE environment variable before starting your application
Change the default DB2 instance on your machine by using the command db2set -g DB2INSTDEF=db2inst1 (** see note below)
Use a TCPIP connection string (as described by #Bhaarat) so that your application does not depend on the database catalog for the default instance
Note: Before changing DB2INSTDEF you may want to see what the current value is, by executing the command db2set -all and looking for DB2INSTDEF in the output. Also note that changing the default instance may affect other applications that run on your machine.

refer this url http://www.c-sharpcorner.com/uploadfile/nipuntomar/connection-strings-for-ibm-db2/
your connection string should be something like this
Provider=IBMDADB2;Database=urDataBase;Hostname=urServerAddress;Protocol=TCPIP;Port=50000;
Uid=urUsername;Pwd=urPassword;
in more you can refer this too
http://www.codeproject.com/Articles/4870/Connect-to-DB2-from-Microsoft-NET

My DB2 insatnce name is "db2inst1" and it was working fine when I used DB2 command window.
Now I made following settings and it is working fine now. :-)
Created a port in the C:\Windows\System32\drivers\etc\services file (db2c_db2inst1 50010/tcp)
Set the “TCP/IP Service Name” ( = db2c_db2inst1”) for the instance. Verified using “db2 get dbm cfg” command
Updated the environment variable DB2INSTANCE with the value “db2inst1”
Restarted the machine
Started the instance
ConnectionString
"Provider = IBMDADB2; Database = TIMS; Hostname = localhost; Protocol = TCPIP; Port = 50010; Uid = myUserID; Pwd = myPassword";
CODE
string queryString = "SELECT * FROM DBATABC";
try
{
using (OleDbConnection connection = new OleDbConnection(connectionString))
{
OleDbCommand command = new OleDbCommand(queryString, connection);
connection.Open();
OleDbDataReader reader = command.ExecuteReader();
if (reader.HasRows)
{
while (reader.Read())
{
if (!reader.IsDBNull(0))
{
string companyCode = reader.GetString(0).ToString();
}
}
}
reader.Close();
}
}
Note: Try to create DSN for ODBC and use ODBC connection in a sample SSIS package. This will help in resolving OLEDB connection issues also (that are common to both)

Related

Cannot connect to SQL Server with Windows authentication from C#

I want to connect to SQL Server 2016 using Windows authentication.
I am using C# with this connection string
Server=192.168.1.12,14331;Database=master;Integrated Security=true;Timeout=30
or
Server=serversql\newinstance;Database=master;Integrated Security=true;Timeout=30
The error is a timeout connection.
When using connection with SQL Server authentication like this:
Server=192.168.1.12,14331;Database=master;User Id=***;Password=****;Timeout=30
everything is ok.
Source code C#
var constr = "<connection string>";
using (var connection = new SqlConnection(constr))
{
var command = connection.CreateCommand();
command.CommandType = CommandType.Text;
command.CommandText = "SELECT 1";
command.CommandTimeout = 0;
connection.Open();
command.ExecuteNonQuery();
}
But when I am using SQL Server Management Studio to check connection to the SQL Server instance with Windows authentication, it is ok. Using alias or Ip address does not help the error.
I don't understand why I get this error ...
Help me please! Thanks you everyone!
UPDATE:
If I use connection 1 with IP and port, there is an error:
Login failed. The login is from an untrusted domain and cannot be used
with Windows
UPDATE:
Instance SQL installed on other PC the same network LAN with My PC.
I'm checked Log Viewer on PC install instance SQL but no record log.
I'm not sure it works for you, but you can try it:
SqlConnection cnn;
public connect(){
string strConnect = #"Data Source=192.168.1.12,14331;Network Library=DBMSSOCN;Initial Catalog=master;User ID=****;Password=*****";
cnn = new SqlConnection(strConnect);
try
{
cnn.Open();
}
catch(Exception)
{
// connect failed
}
}
public void ExeQuery(string query){
// query="select * from tblA"
SqlCommand sqlCmd = new SqlCommand(query,cnn);
sqlCmd.ExecuteNonQuery();
sql.Dispose();
}

Cannot connect to Azure MySQL database from .NET Connector

I tried to connect to the Azure MySQL database using MySQL Workbench and MySQL Shell and it works fine. Now I am trying to connect using following C# code:
var connStringBuilder = new MySqlConnectionStringBuilder
{
Server = "creatur-db.mysql.database.azure.com",
Database = "test",
UserID = "creatur_db_main#creatur-db",
Password = "{my_password}",
SslMode = MySqlSslMode.Preferred,
};
using (MySqlConnection connection = new MySqlConnection(connStringBuilder.ToString()))
{
connection.Open();
connection.Close();
}
Here I replaced {my_password} with password to the database and it gives me an exception inside Open method:
MySql.Data.MySqlClient.MySqlException: 'Authentication to host
'creatur-db.mysql.database.azure.com' for user
'creatur_db_main#creatur-db' using method 'mysql_native_password'
failed with message: The connection string may not be right. Please
visit portal for references.
I also tried different connection strings:
Server=creatur-db.mysql.database.azure.com; Port=3306; Database=test; Uid=creatur_db_main#creatur-db; Pwd={my_password}; SslMode=Preferred
and
Database=test; Data Source=creatur-db.mysql.database.azure.com; User Id=creatur_db_main#creatur-db; Password={my_password}
But none of them worked.
The same exception occurs when I create new connection using Server Explorer in Visual Studio 2013. It seems the error has something to do with .NET Connector. I tried to use different versions of MySQL.Data.dll, .NET Framework and Visual Studio but no luck.
I just created a console application using VS2017 I used
Nuget package MySql.Data and .Net Framework 4.6.1
It works perfectly here What I did.
After Creating the MySQL server I used the CloudShell to connect to the SERVER (not a database).
Using this code:
mysql --host franktest.mysql.database.azure.com --user frank#franktest -p
I got an error
ERROR 9000 (HY000): Client with IP address '40.76.202.47' is not allowed to connect to this MySQL server.
So I add that IP and at the same time my IP from where I'm connected.
So once the IP were saved. I executed the previous command, and this time it worked perfectly. I created a database named: frankdemo using this command:
CREATE DATABASE frankdemo;
Then, back in VisualStudio used this code as my Main method, copied from the documentation.
static void Main(string[] args)
{
var builder = new MySqlConnectionStringBuilder
{
Server = "franktest.mysql.database.azure.com",
Database = "frankdemo",
UserID = "frank#franktest",
Password = "gr3enRay14!",
SslMode = MySqlSslMode.Required,
};
using (var conn = new MySqlConnection(builder.ConnectionString))
{
Console.WriteLine("Opening connection");
conn.Open();
using (var command = conn.CreateCommand())
{
command.CommandText = "DROP TABLE IF EXISTS inventory;";
command.ExecuteNonQuery();
Console.WriteLine("Finished dropping table (if existed)");
command.CommandText = "CREATE TABLE inventory (id serial PRIMARY KEY, name VARCHAR(50), quantity INTEGER);";
command.ExecuteNonQuery();
Console.WriteLine("Finished creating table");
command.CommandText = #"INSERT INTO inventory (name, quantity) VALUES (#name1, #quantity1),
(#name2, #quantity2), (#name3, #quantity3);";
command.Parameters.AddWithValue("#name1", "banana");
command.Parameters.AddWithValue("#quantity1", 150);
command.Parameters.AddWithValue("#name2", "orange");
command.Parameters.AddWithValue("#quantity2", 154);
command.Parameters.AddWithValue("#name3", "apple");
command.Parameters.AddWithValue("#quantity3", 100);
int rowCount = command.ExecuteNonQuery();
Console.WriteLine(String.Format("Number of rows inserted={0}", rowCount));
}
// connection will be closed by the 'using' block
Console.WriteLine("Closing connection");
}
Console.WriteLine("Press RETURN to exit");
Console.ReadLine();
}
Runed it and it works
The documentation I'm referring to is:
Create an Azure Database for MySQL server by using the Azure portal
Azure Database for MySQL: Use .NET (C#) to connect and query data

Connecting to mysql on 000webhost using C#

Im simply just trying to read what there is in the batabase on to a console but i always get an exception on the conn.Open() line. Here is all the code:
SqlConnectionStringBuilder conn_string = new SqlConnectionStringBuilder();
conn_string.DataSource = "mysql14.000webhost.com"; // Server
conn_string.UserID = "a7709578_codecal";
conn_string.Password = "xxxxx";
conn_string.InitialCatalog = "a7709578_codecal"; // Database name
SqlConnection conn = new SqlConnection(conn_string.ToString());
conn.Open();
SqlCommand cmd = new SqlCommand("Select name FROM Users");
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
Console.WriteLine("{1}, {0}", reader.GetString(0), reader.GetString(1));
}
reader.Close();
conn.Close();
if (Debugger.IsAttached)
{
Console.ReadLine();
}
You need to build the connection string manually or use MySqlConnectionStringBuilder. MySql uses a different format than SQL Server and the SqlConnectionStringBuilder that you're using. You also need to use a MySQL library, SqlConnection, SqlCommand, etc are all build specifically for SQL Server.
MySQL connectors
For MySQL database you are using wrong provider. Those classes you have used in posted code are for SQL Server. Your code should look like below with MySQL provider related classes
MySqlConnectionStringBuilder conn_string = new MySqlConnectionStringBuilder();
conn_string.Server = "mysql14.000webhost.com";
conn_string.UserID = "a7709578_codecal";
conn_string.Password = "xxxxxxx";
conn_string.Database = "a7709578_codecal";
using (MySqlConnection conn = new MySqlConnection(conn_string.ToString()))
Check Related post in SO
Also to point out, you are selecting only one column from your table as can be seen
new SqlCommand("Select name FROM Users");
Whereas trying to retrieve two column value, which is not correct
Console.WriteLine("{1}, {0}", reader.GetString(0), reader.GetString(1))
000webhost free servers does not allow external connections to the server database.
You can only use your database from your PHP scripts stored on the server.
You can get data from database using PHP and it will return.So i advice to you using php from C# like api.

Error While Adding DataSource in Data Connections

When I tried to add a connection it is showing the following error as shown in the attachment. “Unable to open the physical file. Access is Denied” .
When I searched about it, it suggest for adding the SQL Server’s account to the folder. Then, using the following query I found that the account is “LocalSystem”. When I tried to add “LocalSystem” to ACL of the folder, such an account is not available. How do we resolve it and add the connection to DBML?
Note: When I used DataReader with the database name in a C# program, it worked well.
Query Used:
declare #sqlser varchar(20)
EXEC master..xp_regread #rootkey='HKEY_LOCAL_MACHINE',
#key='SYSTEM\CurrentControlSet\Services\MSSQLSERVER',
#value_name='objectname', #value=#sqlser OUTPUT
SELECT convert(varchar(30),#sqlser)
Working C# Program:
SqlDataReader rdr = null;
SqlConnection con = null;
SqlCommand cmd = null;
try
{
// Open connection to the database
string ConnectionString = "server=D088DTRV;integrated security=true; database=BankAccount";
con = new SqlConnection(ConnectionString);
con.Open();
string CommandText = "SELECT * FROM Account";
cmd = new SqlCommand(CommandText);
cmd.Connection = con;
rdr = cmd.ExecuteReader();
while (rdr.Read())
{
string test = rdr["AccountType"].ToString();
}
}
The problem was related to Data Connections.
In the advanced window, when I checked, it was trying for ./SQLExpress. I modified it with ".".
I restarted the machine. I also stopped the SQLExpress in the services.msc
Data Source=.;AttachDbFilename=C:\DevTEST\Databases\LibraryReservationSystem.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True

Create an SQL Express 2008 database in C# code, but login fails when trying to connect with a sysadmin

I have a piece of code that creates an SQL Server Express 2008 in runtime, and then tries to connect to it to execute a database initialization script in Transact-SQL. The code that creates the database is the following:
private void CreateDatabase()
{
using (var connection = new SqlConnection(
"Data Source=.\\sqlexpress;Initial Catalog=master;" +
"Integrated Security=true;User Instance=True;"))
{
connection.Open();
using (var command = connection.CreateCommand())
{
command.CommandText =
"CREATE DATABASE " + m_databaseFilename +
" ON PRIMARY (NAME=" + m_databaseFilename +
", FILENAME='" + this.m_basePath + m_databaseFilename + ".mdf')";
command.ExecuteNonQuery();
}
}
}
The database is created successfully. After that, I try to connect to the database to run the initialization script, by using the following code:
private void ExecuteQueryFromFile(string filename)
{
string queryContent = File.ReadAllText(m_filePath + filename);
this.m_connectionString = string.Format(
#"Server=.\SQLExpress; Integrated Security=true;Initial Catalog={0};", m_databaseFilename);
using (var connection = new SqlConnection(m_connectionString))
{
connection.Open();
using (var command = connection.CreateCommand())
{
command.CommandText = queryContent;
command.CommandTimeout = 0;
command.ExecuteNonQuery();
}
}
}
However, the connection.Open() statement fails, throwing the following exception:
Cannot open database "TestData"
requested by the login. The login
failed. Login failed for user
'MYDOMAIN\myusername'.
I am completely puzzled by this error because the account I am trying to connect with has sysadmin privileges, which should allow me to connect any database (notice that I use a connection to the master database to create the database in the first place).
Is there a reason you specify User Instance=True when you create it but not when you try to connect to it?
When you create it after connecting with User Instance, it will create the database files but does not attach it to your actual instance. You'll either have to not specify User Instance=True in the first connection string or add it to the second and specify the database file to use.
Is the user you are logging with have rights to the database 'TestData'?
If not grant the user the privileges required.
I am not sure if this means anything, but in your first create you are connecting to server
.\\sqlexpress
The second one is
.\SQLExpress
You'll need to issue a CREATE USER command (see: http://msdn.microsoft.com/en-us/library/ms173463.aspx) after creating the database but before trying to open a connction to that database.
For example:
CREATE USER 'MYDOMAIN\myusername' FOR LOGIN 'MYDOMAIN\myusername'

Categories