How can I make my DB connection works? - mysql

I set up a MySQL database in my AZURE account, but I cannot connect it in any way. I tried:
namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
SqlConnection sqlconnection = new SqlConnection("Database=Banco1; Data Source=br-cdbr-azure-south-a.cloudapp.net;User Id=USERID Password=PASSWORDid");
Console.WriteLine("1");
sqlconnection.Open();
Console.WriteLine("2");
SqlCommand cmd = new SqlCommand("CREATE TABLE Customer(First_Name char(50), Last_Name char(50), Address char(50), City char(50), Country char(25), Birth_Date datetime); ", sqlconnection);
Console.WriteLine("3");
cmd.ExecuteNonQuery();
Console.WriteLine("4");
Console.ReadLine();
}
}
}
I tried putting prints through the commands, and the program only prints "1" wich means I can't get the connection opened... how can I fix that?
The output error:
An unhandled exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll
Additional information: Error in the network or specifics to the instance when stablishing conexion to the SQL Server. The server was not found or was not avaible. Check if the instance name is correct and if the SQL Server is configured to allow remote conexions. (provider: Named Pipes Provider, error: 40 - Could not stablish connection to SQL Server)

SqlConnection is used for connecting SQL Database, for MySQL Database, you need to use MySqlConnection. Please first install MySql Connect/NET and then add reference
Now you can connect to your Mysql database successfully with the code below:
MySqlConnection con = new MySqlConnection("your_mysql-connect_string");

Related

A network-related or instance-specific error occurred while establishing a connection to SQL Server. Code-first ef core 6

I am building my first application using .Net 6 EF Core.
I want to use the code-first method.
When I try to migrate using Update-Database (after I get this error:
A network-related or instance-specific error occurred while
establishing a connection to SQL Server. The server was not found or
was not accessible. Verify that the instance name is correct and that
SQL Server is configured to allow remote connections. (provider: Named
Pipes Provider, error: 40 - Could not open a connection to SQL Server)
I have a "local instance of MySQL80" running on my machine. I can connect to it, using a DB tool, like Dbeaver or the MySQL Workbench.
This is the Connection String I am using:
"ConnectionStrings": {
"DevConnection": "Server=localhost;Database=my-desired-db-name;Trusted_Connection=True;"
}
This is my Program.cs:
using Microsoft.EntityFrameworkCore;
using react_chores_prototype_api.Models;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
builder.Services.AddDbContext<MyDBContext>(options => options.UseSqlServer(builder.Configuration.GetConnectionString("DevConnection")));
var app = builder.Build();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
app.UseAuthorization();
app.MapControllers();
app.Run();
I know that this question came up a few times already, but I cant find a solution with the given explantations, also because of lots of different versions over the years. If someone can maybe help me, so i can start working on my project, that would be greatly appreciated.
EDIT:
I installed Pomelo MySql Provider and changed the connectionString to a mysql one.
Also i changed my Program.cs like this:
var conString = "Server=localhost;Database=my-db-name;Uid=root;Pwd=verySecurePw;";
builder.Services.AddDbContext<MyDBContext>(options => options.UseMySql(connectionString: conString, ServerVersion.AutoDetect(conString)));
Now it seems to work, I just get following SQL Syntax Error (Not really related to the original Question I guess):
You have an error in your SQL syntax; check the manual that
corresponds to your MySQL server version for the right syntax to use
near 'NOT NULL,
Description nvarchar(200 NOT NULL,
Points int NOT NULL,
Related to this Model:
using Microsoft.EntityFrameworkCore.Metadata.Internal;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace react_chores_prototype_api.Models
{
public class Task
{
[Key]
public int Id { get; set; }
[Column(TypeName = "nvarchar(50)"]
public string Name { get; set; }
[Column(TypeName = "nvarchar(200)"]
public string Description { get; set; }
public int Points { get; set; }
}
}

Is there any Dremio or Drill connection string for C# or .NET program user

I am using dremio to query a large amount of data and it is working very fine. It has rest API to fetch data but the only constraint is that it can give 500 records as a result. In java, Dremio community has given jdbc connection string but our project is in .net or c# so we need the connection string to fetch the massive amount of data from dremio. If the connection string is not there for C# then can anyone suggest us how do we use JDBC connection string in C#.
Drill and Dremio have ODBC interface for that purpose, see:
https://drill.apache.org/docs/configuring-odbc/
https://docs.dremio.com/drivers/dremio-odbc-driver.html
So you can setup up your C# project to use ODBC connection string instead of JDBC:
https://support.office.com/en-us/article/connect-to-an-odbc-source-49b0cf4d-ef78-4ad1-b224-39091c067953
or programmatically:
static private void InsertRow(string connectionString)
{
string queryString =
"INSERT INTO Customers (CustomerID, CompanyName) Values('NWIND', 'Northwind Traders')";
OdbcCommand command = new OdbcCommand(queryString);
using (OdbcConnection connection = new OdbcConnection(connectionString))
{
command.Connection = connection;
connection.Open();
command.ExecuteNonQuery();
// The connection is automatically closed at
// the end of the Using block.
}
}
where connection string examples:
DRIVER=MapR Drill ODBC
Driver;AdvancedProperties={HandshakeTimeout=0;QueryTimeout=0;TimestampTZDisplayTimezone=utc;ExcludedSchemas=sys,INFORMATION_SCHEMA;};Catalog=DRILL;Schema=hivestg;ConnectionType=Direct;Host=192.168.202.147;Port=31010
DRIVER=MapR Drill ODBC
Driver;AdvancedProperties={HandshakeTimeout=0;QueryTimeout=0;TimestampTZDisplayTimezone=utc;ExcludedSchemas=sys,
INFORMATION_SCHEMA;};Catalog=DRILL;Schema=;ConnectionType=ZooKeeper;ZKQuorum=192.168.39.43:5181;ZKClusterID=drillbits1

Stored procedure with referenced linkedserver

I am fighting with stored procedure with referenced linkedserver. Linked server is accesible over internet via port forwarding - so no VPN, LAN.
Servers are on both sides MS SQL SERVER 2008 EE v. 10.0.5512
Configurations Linked server, DTC:
cannot insert images yet:(
enable promotion of distributed transaction = false
RPC = false
RPC out = false
Network DTC Access checked
Allow inbound true
Allow outbound true
No authentication Required
Stored procedure looks like
CREATE PROCEDURE [dbo].[spSynchronizeArticles]
-- Add the parameters for the stored procedure here
(
#pDebug bit,
#siteId bigint
)
AS
BEGIN
SELECT *
FROM [LinkedServer].[MyDatabase].dbo.Storages
WHERE Storage.siteId = #siteId
RETURN 0
END
As you can see no transaction here. If I am correct the MS DTC is creating transaction every time when the linked server is called.
I am calling this procedure from c# like this
SqlCommand sqlCmd = new SqlCommand("spSynchronizeArticles");
sqlCmd.CommandType = CommandType.StoredProcedure;
sqlCmd.Parameters.AddWithValue("#pDebug", false);
sqlCmd.Parameters.AddWithValue("#siteId", siteId);
SqlParameter returnValue = new SqlParameter("returnVal", SqlDbType.Int);
returnValue.Direction = ParameterDirection.ReturnValue;
sqlCmd.Parameters.Add(returnValue);
using (SqlConnection conn = new SqlConnection(Context.LocalData.ConnectionString))
{
try
{
try
{
conn.Open();
sqlCmd.Connection = conn;
sqlCmd.ExecuteScalar();
return Convert.ToInt32(returnValue.Value);
}
catch (Exception ex)
{
//log exception to file
return -1;
}
}
finally
{
conn.Close();
}
}
}
This c# code is called in infinite while to synchronize data. In same Thread and while there is also another method called which is getting data from file (if any exist) and saving them to local DB.
The SynchronizeArticles method is invoking more often and everything is working, but once the method for getting data from file is called, the SynchronizeArticles always throw this exception
System.Data.SqlClient.SqlException (0x80131904): MSDTC on server
'LocalServer\SQLEXPRESS2008' is unavailable.
The method is using Transaction and looks like
public void FillDataFromViewWithTrans(DataTable dt, string wherePhrase)
{
dt.Rows.Clear();
SqlCommand sql = new SqlCommand(String.Format(#"SELECT *
FROM SomeView
{0}", String.IsNullOrEmpty(wherePhrase) ? String.Empty : "WHERE " + wherePhrase));
using (SqlConnection conn = new SqlConnection(Context.LocalData.ConnectionString))
{
SqlTransaction trans = null;
try
{
try
{
conn.Open();
trans = conn.BeginTransaction(IsolationLevel.RepeatableRead);
sql.Transaction = trans;
sql.Connection = conn;
SqlDataAdapter dA = new SqlDataAdapter(sql);
dA.Fill(dt);
trans.Commit();
}
catch (Exception ex)
{
trans.Rollback();
//log exception to file
return;
}
}
finally
{
conn.Close();
}
}
}
This is just illustration samples :)
Tell me what I am missing.
Additionally I have big troubles with the MS DTC with various errors
From C# code when some users calls the procedure manually they sometimes got exception:
The operation could not be performed because the OLE DB provider
'SQLOLEDB' was unable to begin a distributed transaction.
When I put the begin distributed transaction inside the stored procedure I got:
Warning: Fatal error 8510 occurred at Apr 10 2013 9:07AM. Note the
error and time, and contact your system administrator.
What only helps is the restart of the windows service or the UI application. From the MS SQL management studio the procedure works all the time without problems.
Now I must say I am desperate, what am I missing?
Edit:
int i = 0;
while (true)
{
i++;
if ((i % 9) == 0)
{
//local select with transaction Works all the time
CallLocalSelectWithTransaction();
}
// CallProcedure works 8 times, after first calling of CallLocalSelectWithTransaction
// the callProcedure works no more.
CallProcedure(); // procedure with linked server
}

Creating a DSN-less connection for MS Access within Java

I'm building a desktop app that needs to communicate with a MS Access database. Now, unless I want to register the DSN for the database on every computer that's going to use the desktop app, I need a way to connect to the database in a DSN-less fashion.
I've searched alot and found some useful links on how to create connection strings and based on that I tried modifying my program based on that but without success.
The code below fails. If i switch the string in the getConnection to "jdbc:odbc:sampleDB" it works, but that's using DSN and not what I want to achieve.
How do I write and use a connection string in java to make a DSN-less connection to a MS Access database?
private Connection setupConnection() throws ClassNotFoundException,
SQLException {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con = DriverManager.getConnection("Driver={Microsoft Access Driver (*.mdb)} &_ Dbq=c:\\as\\sampleDB.mdb");
return con;
}
Addition: I'd also like to point out that if anyone has an idea of a way to achieve what I asked for WITH a DSN-connection I'll gladly listen to it!
JDBC connection string shouls start with jdbc: like:
jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)};DBQ=c:\\Nwind.mdb
so try with:
Connection con = DriverManager.getConnection("jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)};Dbq=c:\\as\\sampleDB.mdb");
If you configure DSN then you can connect to it using simplier connect string: jdbc:odbc:[alias], example:
jdbc:odbc:northwind
I also had this problem and tried many of the suggestions here and on various forums. Finally, I discovered a snippet from one place which led to success connecting and also explains why many of these posts do not work. See http://www.coderanch.com/t/295299/JDBC/databases/jdbc-odbc-DSN-connection-MS
The issue is that there must be a semicolon after the colon at the end of odbc as in jdbc:odbc:;Driver= . This made sense after reading the Oracle documentation on the JdbcOdbc bridge which states that the syntax is jdbc:odbc:dsn; attributes....... Since we are not supplying a DSN, then we need to end with ; before adding attributes.
I am showing below the tests I ran with different connection strings on a Windows 7 Ultimate 32bit machine:
driver= (Driver)Class.forName("sun.jdbc.odbc.JdbcOdbcDriver").newInstance();
//jdbc:odbc:Driver={Microsoft Access Driver (*.mdb, *.accdb)};DBQ= does lookup to ODBC.ini to find matching driver
try {
connstr= "jdbc:odbc:;Driver={Microsoft Access Driver (*.mdb, *.accdb)};DBQ=" + fileURI; //64 bit ?? (*.mdb,*.accdb)
conn= DriverManager.getConnection(connstr, "", "");
stmt= conn.createStatement();
}
catch (Exception e){}
try {
connstr= "jdbc:odbc:;Driver={Microsoft Access Driver (*.mdb)};DBQ=" + fileURI; //64 bit ?? (*.mdb,*.accdb)
conn1= DriverManager.getConnection(connstr, "", "");
stmt1= conn1.createStatement();
dbmeta1=conn1.getMetaData();
}
catch (Exception e){}
try {
connstr= "jdbc:odbc:MS Access Database;DBQ=" + fileURI; //64 bit ?? (*.mdb,*.accdb)
conn2= DriverManager.getConnection(connstr, "", "");
stmt2= conn2.createStatement();
dbmeta2=conn2.getMetaData();
}
catch (Exception e){}
try {
connstr= "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)};DBQ=" + fileURI; //64 bit ?? (*.mdb,*.accdb)
conn3= DriverManager.getConnection(connstr, "", "");
stmt3= conn3.createStatement();
dbmeta3=conn3.getMetaData();
}
catch (Exception e){}
stmt1 and stmt3 are null since the connections are null. stmt and stmt2 work. stmt2 uses a connection string I found in the documentation for IBM Tivoli. It works because "MS Access Database" is a valid title in the ODBC registry as a User DSN on my computer.

What is the MySQL JDBC driver connection string?

I am new to JDBC and I am trying to make a connection to a MySQL database.
I am using Connector/J driver, but I cant find the JDBC connection string for my Class.forName() method.
Assuming your driver is in path,
String url = "jdbc:mysql://localhost/test";
Class.forName ("com.mysql.jdbc.Driver").newInstance ();
Connection conn = DriverManager.getConnection (url, "username", "password");
Here's the documentation:
https://dev.mysql.com/doc/connector-j/en/connector-j-reference-configuration-properties.html
A basic connection string looks like:
jdbc:mysql://localhost:3306/dbname
The class.forName string is "com.mysql.jdbc.Driver", which you can find (edit: now on the same page).
"jdbc:mysql://localhost"
From the oracle docs..
jdbc:mysql://[host][,failoverhost...]
[:port]/[database]
[?propertyName1][=propertyValue1]
[&propertyName2][=propertyValue2]
host:port is the host name and port number of the computer hosting your database. If not specified, the default values of host and port are 127.0.0.1 and 3306, respectively.
database is the name of the database to connect to. If not specified, a connection is made with no default database.
failover is the name of a standby database (MySQL Connector/J supports failover).
propertyName=propertyValue represents an optional, ampersand-separated list of properties. These attributes enable you to instruct MySQL Connector/J to perform various tasks.
It is very simple :
Go to MySQL workbench and lookup for Database > Manage Connections
you will see a list of connections. Click on the connection you wish to connect to.
You will see a tabs around connection, remote management, system profile. Click on connection tab.
your url is jdbc:mysql://<hostname>:<port>/<dbname>?prop1 etc.
where <hostname> and <port> are given in the connection tab.It will mostly be localhost : 3306. <dbname> will be found under System Profile tab in Windows Service Name. Default will mostly be MySQL5<x> where x is the version number eg. 56 for MySQL5.6 and 55 for MySQL5.5 etc.You can specify ur own Windows Service name to connect too.
Construct the url accordingly and set the url to connect.
For Mysql, the jdbc Driver connection string is com.mysql.jdbc.Driver. Use the following code to get connected:-
class DBConnection {
private static Connection con = null;
private static String USERNAME = "your_mysql_username";
private static String PASSWORD = "your_mysql_password";
private static String DRIVER = "com.mysql.jdbc.Driver";
private static String URL = "jdbc:mysql://localhost:3306/database_name";
public static Connection getDatabaseConnection(){
Class.forName(DRIVER);
return con = DriverManager.getConnection(URL,USERNAME,PASSWORD);
}
}
As the answer seems already been answered, there is not much to add but I would like to add one thing to the existing answers.
This was the way of loading class for JDBC driver for mysql
com.mysql.jdbc.Driver
But this is deprecated now. The new driver class is now
com.mysql.cj.jdbc.Driver
Also the driver is automatically registered via the SPI and manual loading of the driver class is generally unnecessary.
update for mySQL 8 :
String jdbcUrl="jdbc:mysql://localhost:3306/youdatabase?useSSL=false&serverTimezone=UTC";
Here is a little code from my side :)
needed driver:
com.mysql.jdbc.Driver
download: here (Platform Independent)
connection string in one line:
jdbc:mysql://localhost:3306/db-name?user=user_name&password=db_password&useSSL=false
example code:
public static void testDB(){
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
try {
Connection connection = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/db-name?user=user_name&password=db_password&useSSL=false");
if (connection != null) {
Statement statement = connection.createStatement();
if (statement != null) {
ResultSet resultSet = statement.executeQuery("select * from test");
if (resultSet != null) {
ResultSetMetaData meta = resultSet.getMetaData();
int length = meta.getColumnCount();
while(resultSet.next())
{
for(int i = 1; i <= length; i++){
System.out.println(meta.getColumnName(i) + ": " + resultSet.getString(meta.getColumnName(i)));
}
}
resultSet.close();
}
statement.close();
}
connection.close();
}
} catch (Throwable throwable) {
throwable.printStackTrace();
}
}
update for mySQL 8 :
String jdbcUrl="jdbc:mysql://localhost:3306/youdatabase?useSSL=false&serverTimezone=UTC";
Check whether your Jdbc configurations and URL correct or wrong using the following code snippet.
import java.sql.Connection;
import java.sql.DriverManager;
public class TestJdbc {
public static void main(String[] args) {
//db name:testdb_version001
//useSSL=false (get rid of MySQL SSL warnings)
String jdbcUrl = "jdbc:mysql://localhost:3306/testdb_version001?useSSL=false";
String username="testdb";
String password ="testdb";
try{
System.out.println("Connecting to database :" +jdbcUrl);
Connection myConn =
DriverManager.getConnection(jdbcUrl,username,password);
System.out.println("Connection Successful...!");
}catch (Exception e){
e.printStackTrace();
//e.printStackTrace();
}
}
}
The method Class.forName() is used to register the JDBC driver. A connection string is used to retrieve the connection to the database.
The way to retrieve the connection to the database is shown below. Ideally since you do not want to create multiple connections to the database, limit the connections to one and re-use the same connection. Therefore use the singleton pattern here when handling connections to the database.
Shown Below shows a connection string with the retrieval of the connection:
public class Database {
private String URL = "jdbc:mysql://localhost:3306/your_db_name"; //database url
private String username = ""; //database username
private String password = ""; //database password
private static Database theDatabase = new Database();
private Connection theConnection;
private Database(){
try{
Class.forName("com.mysql.jdbc.Driver"); //setting classname of JDBC Driver
this.theConnection = DriverManager.getConnection(URL, username, password);
} catch(Exception ex){
System.out.println("Error Connecting to Database: "+ex);
}
}
public static Database getDatabaseInstance(){
return theDatabase;
}
public Connection getTheConnectionObject(){
return theConnection;
}
}
String url = "jdbc:mysql://localhost:3306/dbname";
String user = "user";
String pass = "pass";
Class.forName ("com.mysql.jdbc.Driver").newInstance ();
Connection conn = DriverManager.getConnection (url, user, pass);
3306 is the default port for mysql.
If you are using Java 7 then there is no need to even add the Class.forName("com.mysql.jdbc.Driver").newInstance (); statement.Automatic Resource Management (ARM) is added in JDBC 4.1 which comes by default in Java 7.
The general format for a JDBC URL for connecting to a MySQL server is as follows, with items in square brackets ([ ]) being optional:
jdbc:mysql://[host1][:port1][,[host2][:port2]]...[/[database]] ยป
[?propertyName1=propertyValue1[&propertyName2=propertyValue2]...]
protocol//[hosts][/database][?properties]
If you don't have any properties ignore it then it will be like
jdbc:mysql://127.0.0.1:3306/test
jdbc:mysql is the protocol
127.0.0.1: is the host and 3306 is the port number
test is the database
it's depends on what service you're using.
if you use MySQL Workbench it wold be some thing like this :
jdbc:mysql://"host":"port number"/
String url = "jdbc:mysql://localhost:3306/";
And of course it will be different if you using SSL/SSH.
For more information follow the official link of Jetbriens (intelliJ idea) :
Connecting to a database #
https://www.jetbrains.com/help/idea/connecting-to-a-database.html
Configuring database connections #
https://www.jetbrains.com/help/idea/configuring-database-connections.html
Check if the Driver Connector jar matches the SQL version.
I was also getting the same error as I was using the
mySQl-connector-java-5.1.30.jar
with MySql 8