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
Related
I have built a web api using dotnet and this is my first time using Azure (or any other cloud platform) to host web applications. I've used EntityFramework and MySQL database with to build my project.
I used DbConnectionString = "Server=localhost;Database=hms;Uid='{root-user}';Pwd={pw};" as the connection string of my SQL Database and now I'm wondering how can I connect it with the Azure SQL Database I have created. I added my IP address in firewall access in the Azure server and tried changing the connection string as DbConnectionString = "Server=server.database.windows.net:1433;Database=hms;Uid='{root-user}';Pwd={pw};" but it gives an error An exception has been raised that is likely due to a transient failure. Consider enabling transient error resiliency by adding 'EnableRetryOnFailure()' to the 'UseMySql' call. when I'm trying to update the database after adding migrations.
I'd like to know what I have done wrong or what else I need to do in order to get this running. tyia.
I have created an Azure SQL database with one table.
Table is having data as below
3.Created Console application using C#.
Added Package Microsoft.Data.SqlClient to the Project.
Added following code in Program.cs file,
[Taking reference from here](https://learn.microsoft.com/en-us/azure/azure-sql/database/connect-query-dotnet-visual-studio?view=azuresql), I created a replica of the program.cs file as shown:
using System;
using Microsoft.Data.SqlClient;
using System.Text;
namespace sqltest
{
class Program
{
static void Main(string[] args)
{
try
{
SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder();
builder.DataSource = "yourservername.database.windows.net";
builder.UserID = "your_username";
builder.Password = "your_password";
builder.InitialCatalog = "your_database";
using (SqlConnection connection = new SqlConnection(builder.ConnectionString))
{
Console.WriteLine("\nQuery data example:");
Console.WriteLine("=========================================\n");
//String sql = "SELECT * FROM dbo.Persons";
String sql = "SELECT LastName, FirstName FROM dbo.Persons";
using (SqlCommand command = new SqlCommand(sql, connection))
{
connection.Open();
using (SqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
Console.WriteLine("{0} {1}", reader.GetString(0), reader.GetString(1));
}
}
}
}
}
catch (SqlException e)
{
Console.WriteLine(e.ToString());
}
Console.ReadLine();
}
}
}
6.Using above code, I am connecting to Azure SQL and retrieving data from database.
Run the application and getting data from Azure Sql data base as shown below,
Reference links:
https://learn.microsoft.com/en-us/visualstudio/azure/azure-sql-database-add-connected-service?view=vs-2022
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.
I have a SQL CLR trigger written in C# 4.0 and deployed on SQL Server 2014. Whenever an insertion happens in a table in SQL Server, this CLR trigger's job is to import that row in an Oracle database. So basically I have to import data in Oracle database whenever an insert query is fired on a table in SQL Server 2014. This is my first CLR SQL trigger project and below is what I am doing:
[SecurityCritical]
[OraclePermission(System.Security.Permissions.SecurityAction.Assert, Unrestricted = true)]
[SqlTrigger(Name = "FetchSurvey", Target = "temp", Event = "FOR INSERT")]
public static void FetchSurvey()
{
SqlTriggerContext triggerContext = SqlContext.TriggerContext;
// Create result set to store data
DataSet resultSet = new DataSet();
// Create a new SQL command
using (SqlCommand command = new SqlCommand("SELECT * FROM INSERTED"))
{
// Create a new SQL connection
using (command.Connection = new SqlConnection("context connection=true"))
{
// Connect to the database
command.Connection.Open();
// Execute procedure
using (SqlDataAdapter adapter = new SqlDataAdapter(command))
{
adapter.Fill(resultSet);
}
// Disconnect from the database
command.Connection.Close();
}
}
SqlPipe sqlP = SqlContext.Pipe;
// Return data
if (resultSet.Tables.Count > 0)
SaveSurvey(resultSet);
sqlP.Send("Finaly its done!!");
}
public static void SaveSurvey(DataSet dsSurvey)
{
using (OracleConnection con = new OracleConnection("my oracle connection string"))
{
if (con.State == ConnectionState.Closed)
con.Open();
DataRowView drv = dsSurvey.Tables[0].DefaultView[0];
using (OracleCommand cmd = new OracleCommand("AddMetaData", con))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("V_id", drv["TemplateID"]);
cmd.Parameters.AddWithValue("V_Title", drv["TemplateName"]);
cmd.Parameters.AddWithValue("V_CreatedBy", drv["CreatedBy"]);
cmd.Parameters.AddWithValue("V_IsActive", drv["IsActive"]);
cmd.ExecuteNonQuery();
}
}
}
And this is my code to create assembly/deploy trigger:
CREATE ASSEMBLY TriggerImportSurvey
FROM 'C:\ImportSurvey\SQL-CLR-Trigger.dll'
With Permission_Set = External_Access;
Now the problem is whenever I run an insert query in SQL Server to insert data, I got below error in SQL Server:
Msg 6522, Level 16, State 1, Procedure tri_InsertSurvey_clr, Line 18
A .NET Framework error occurred during execution of user-defined routine or aggregate "tri_InsertSurvey_clr":
System.InvalidOperationException: Cannot perform CAS Asserts in Security Transparent methods
System.InvalidOperationException:
at Triggers.FetchSurvey()
tri_InsertSurvey_clr is the trigger which is responsible for executing the assembly whenever I run an insert statement.
Please tell me what I am missing so that I am getting this error, Also if there a more elegant way of implementing a CLR SQL trigger then please also suggest that.
NOTE: When I tried to save the data using a trigger in SQL Server I was successful, but now when I am trying to save it in Oracle database, I am getting this error. Also the Oracle database is installed on another machine.
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)
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'