Xamarin, MySQL exception: unable to connect to any specific host - c#

I want to make an simple app that will get data out of remote database and show it on a screen, so first I made a simple console app to test connection and it all works. here's code :
static void Main(string[] args)
{
MySqlConnection con = new MySqlConnection("SERVER=85.10.205.173; PORT=3306; DATABASE=mybasework; UID=neawin; PWD=12345678; old guids=true; Connection Timeout=30;");
try
{
if(con.State == ConnectionState.Closed)
{
con.Open();
MySqlCommand command = new MySqlCommand("SELECT * FROM motto", con);
using (MySqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
Console.WriteLine(reader["motto"]);
}
}
}
}
catch(MySqlException ex)
{
Console.WriteLine(ex.ToString());
}
finally
{
con.Close();
}
}
But then when i tried to test connection on my phone it shows that it is unable to connect to the host, here's code:
using Android.App;
using Android.OS;
using Android.Support.V7.App;
using Android.Runtime;
using Android.Widget;
using MySql.Data.MySqlClient;
using System.Data;
namespace App1
{
[Activity(Label = "#string/app_name", Theme = "#style/AppTheme", MainLauncher = true)]
public class MainActivity : AppCompatActivity
{
private TextView Textmotto;
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
SetContentView(Resource.Layout.activity_main);
Textmotto = FindViewById<TextView>(Resource.Id.textmotto);
MySqlConnection con = new MySqlConnection("SERVER=85.10.205.173; PORT=3306; DATABASE=mybasework; UID=neawin; PWD=12345678; old guids=true; Connection Timeout=30;");
try
{
if (con.State == ConnectionState.Closed)
{
con.Open();
Textmotto.Text = "Success";
}
}
catch (MySqlException ex)
{
Textmotto.Text = ex.ToString();
}
finally
{
con.Close();
}
}
}
}
I think i tried every variation of connectionstring I could, in first program I used mysql.data library and in phone app I used Xamarin.Mysql Nuget Package if that makes any difference. Sorry for english and poor formatting, my first post.

Its probably a network issue. But please, don't do this. In order to directly connect to a DB, you need to put the password to your db in plain text in your app (even if you encrypt it, the key is in your app). This is totally insecure, and any script kiddie can own your database. If you need data from a database, write a webservice and have the webservice access the db, so you never need to have the authentication information leave your own servers.

thanks for help, I resolved the issue by adding INTERNET permission in my manifest as suggested by Vladyslav.

Related

How to connect UWP to MySQL?

I have a simple UWP app that communicates with MySQL. I am using MySqlConnector. Everything works fine in Debug mode. But after installing the application on (another) PC there is no connection with the database. I did everything as described here. As I understand it, the MySQL library is not copied into the project. What am I doing wrong?
using MySqlConnector;
using System;
using Windows.UI.Xaml.Controls;
namespace MyApp
{
public sealed partial class MainPage : Page
{
public MainPage()
{
this.InitializeComponent();
LoadFromDB();
}
private void LoadFromDB()
{
MySqlConnection connection = new MySqlConnection("server=127.0.0.1; port=3306; database=database; username=root; password=pass;");
MySqlCommand command;
MySqlDataReader reader;
connection.Open();
command = new MySqlCommand("SELECT * FROM Numbers", connection);
reader = command.ExecuteReader();
while (reader.Read())
{
myTextBlock.Text = reader["Num"].ToString();
}
connection.Close();
}
}
}
To maintain security and network isolation, loopback connections for IPC are blocked by default for packaged applications. You should enable loopback connections. For more information about how to enable loopback connections, you can refer to this document

MySql from VS 2017 Unable to create Entity Models from database

I am unable to create Entity Models from database.
It is first time using MySQL from VS2017.
I am following tutorial at
1) https://dev.mysql.com/doc/connector-net/en/connector-net-tutorials-intro.html
2) https://dev.mysql.com/doc/connector-net/en/connector-net-tutorials-entity-framework-winform-data-source.html
3) https://dev.mysql.com/doc/connector-net/en/connector-net-entityframework60.html
I installed MySQL on local machine. I installed NuGet packages MySql.Data, MySql.Data.Entity, and MySql.Web (all version 6.9.11).
In tutorial No.2, while adding “ADO.Net Entity Data Model”, I get upto this window
I click next and then window silently close without producing any Data Models.
This means I don’t see the window below.
I assume my connection strting and web.config file is OK as I can successfully execute code bellow and get result “Samoa -- Malietoa Tanumafili II”
`
using System;
using System.Data;
using MySql.Data;
using MySql.Data.MySqlClient;
public class Tutorial2
{
public static void Main()
{
string connStr = "server=localhost;user=root;database=world;port=3306;password=******";
MySqlConnection conn = new MySqlConnection(connStr);
try
{
Console.WriteLine("Connecting to MySQL...");
conn.Open();
string sql = "SELECT Name, HeadOfState FROM Country WHERE Continent='Oceania'";
MySqlCommand cmd = new MySqlCommand(sql, conn);
MySqlDataReader rdr = cmd.ExecuteReader();
while (rdr.Read())
{
Console.WriteLine(rdr[0]+" -- "+rdr[1]);
}
rdr.Close();
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
conn.Close();
Console.WriteLine("Done.");
}
}`
Please guide what I am doing wrong.
This is a known bug in MySQL Connector/NET: bug 89338. According to that bug report, there's a bug in the wizard code that should be fixed in the next version, 6.10.7.

how to solve exception for the connection string(local database c#)

ok so the first problem is the connection string itself it has this exception that i do not understand so i tried to put it in a try catch syntax but as i inserted it in the public partial class Form1 : Form the parenthesis are acting up so i inserted it in a function and now the fuction has this error:
Severity Code Description Project File Line Suppression State
Error CS0161 'Form1.connection()': not all code paths return a value Restaurant Management System C:\Users\admin\source\repos\Restaurant Management System\Restaurant Management System\Form1.cs 36 Active
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace Restaurant_Management_System
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
panel1.BackColor = Color.FromArgb(50, Color.Black);
label1.BackColor = Color.FromArgb(30, Color.Beige);
label2.BackColor = Color.FromArgb(0, Color.Black);
Password.BackColor = Color.FromArgb(0, Color.Black);
}
SqlCommand cmd;
SqlDataReader dr;
public SqlConnection connection()
{
try
{
SqlConnection con = new SqlConnection("Data Source=(LocalDB)\\MSSQLLocalDB;AttachDbFilename= \"|Data Directory|\\Coffee(LoginEmployee).mdf\";Integrated Security=True;");
}
catch (Exception ex)
{
MessageBox.Show("Error message: COULD NOT CONNECT STRING: " + ex);
}
}
private string getUsername()
{
SqlConnection con = connection();
cmd = new SqlCommand("SELECT nalue FROM EmployeeLog where Property=Username", con);
dr = cmd.ExecuteReader();
dr.Read();
return dr[0].ToString();
}
private string getPassword()
{
SqlConnection con = connection();
cmd = new SqlCommand("SELECT nalue FROM EmployeeLog where Property=Password", con);
dr = cmd.ExecuteReader();
dr.Read();
return dr[0].ToString();
}
What do i need to replace? why does it not all return a value? if i use the void case it will also have this error that i cannot explicitly convert it to sqlconnection. this is made in the latest visual studio 2017
If you catch the exception, no SqlConnection will be returned. So you could return null after showing the message box.
Then of course, you will need to do a null check after calling connection() so you don't get a null reference exception trying to use it.
You also need to return the connection you are creating:
return new SqlConnection("Data Source=(LocalDB)\\MSSQLLocalDB;AttachDbFilename=|Data Directory|Coffee(LoginEmployee).mdf;Integrated Security=True;");
Note: I don't recommend hard-coding your connection string either! You would normally add the connection string to your app.config/web.config and read it using ConfigurationManager.ConnectionStrings... - this is because you might have different instance names on different machines, or you might want to point to a database on a server rather than local. You will not need to change the code and recompile just to make it work on more than one machine.
There is information on microsoft's class library site (https://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlconnectionstringbuilder.attachdbfilename(v=vs.110).aspx) saying: An error will be generated if a log file exists in the same directory as the data file and the 'database' keyword is used when attaching the primary data file. In this case, remove the log file. Once the database is attached, a new log file will be automatically generated based on the physical path.

SQL connection string in web service c#

Hi I'm having a problem finding the correct connection statement for my web-service to an sql-server database. I'm trying to retrieve data from my database to check a users login details.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using System.Data.SqlClient;
namespace BTC_Service
{
public class UseDatabase
{
SqlConnection sqlConn;
internal Boolean Connect()
{
try
{
sqlConn = new SqlConnection(#"Integrated Security=true; Initial Catalog=BTCFS_DataBase; Data Source=.\SQLEXPRESS;");
sqlConn.Open();
return true;
}
catch (SqlException ex)
{
return false;
}
}
internal void DisconnectDatabase()
{
sqlConn.Close();
}
internal Boolean ExecuteCommand(String query)
{
try
{
SqlCommand cmd = sqlConn.CreateCommand();
cmd.CommandText = query;
cmd.ExecuteNonQuery();
return true;
}
catch (SqlException ex)
{
return false;
}
}
internal SqlDataReader ExecuteQuery(String query)
{
try
{
SqlCommand cmd = sqlConn.CreateCommand();
cmd.CommandText = query;
return cmd.ExecuteReader();
}
catch (SqlException ex)
{
return null;
}
}
}
}
The database is created with sql-server 2008 and the path for it is:
C:\BTCFS_DataBase\db_BTDC_data.mdf
and the log file
C:\BTCFS_DataBase\db_BTDC_log.ldf
There is no password for the database and the code is as follows:
USE master
GO
create database db_BTCFC
ON PRIMARY
(
NAME = 'db_BTCFC_Data',
FILENAME = 'c:\BTCFS_DataBase\db_BTDC_data.mdf',
SIZE = 5MB,
FILEGROWTH = 10%
)
LOG ON
(
NAME = 'db_BTFC_log',
FILENAME = 'c:\BTCFS_DataBase\db_BTDC_log.ldf',
SIZE = 5MB,
FILEGROWTH = 10%
)
GO
Is there any suggestion to what I am doing wrong?
Should I add the database to visual studio in a specific way?
Or am i creating my database in the wrong way?
Thank you in advance.
The fact that you are connected using Integrated Security, means that your local user account on Windows should be authenticated on the SQL server instance which is hosted locally on your machine (evident by the "." in the Data Source, which refers to your local machine). It might be that the setup of your SQL server instance doesn't accommodate windows authentication. Check that your configuration allows for "mixed mode" authentication, i.e. either Windows authentication or username/password authentication...
I found this statement to be more effective than the previous one:
sqlConn = new SqlConnection(#"Integrated Security=SSPI; Initial Catalog=BTCFS_DataBase; Data Source=localhost");
Thanks #Wolfish for the link.

How do I create a MySql database connection that returns results to a text file?

I want to write a MySql statement that will connect to the database, select a column from the table, then output that data to a text file to a specific location on my computer. I have searched the internet for a couple days now and don't seem to find the answer I am looking for. I am fairly new to c#, MySql, and Visual Studio. I am just trying to learn how to write the correct statements and get the desired result. Any help would be greatly appreciated.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MySql.Data.MySqlClient;
using MySql.Data;
using System.Windows.Forms;
using System.IO;
namespace NewPractice
{
public class Connect
{
static void Main()
{
string results = #"server=111.111.11.111; userid=anyone;
password=anypassword; database=anydatabase";
MySqlConnection conn = null;
try
{
conn = new MySqlConnection(results);
conn.Open();
//Console.WriteLine(
File.WriteAllLines(
#"C:\Documents and Settings\anyone\My Documents\Tests\testoutput.txt",
results.ToArray());
}
catch (MySqlException ex)
{
Console.WriteLine("Error: (0)", ex.ToString());
}
finally
{
if (conn != null)
{
conn.Close();
}
}
}
}
}
You're writing the contents of the result string to the file, not the data you're attempting to select. You need to run a sql command and get a SqlDataReader object to write your data to the file.
string results = #"server=111.111.11.111; userid=anyone;
password=anypassword; database=anydatabase";
MySqlConnection connection = new MySqlConnection(results);
MySqlCommand command = connection.CreateCommand();
MySqlDataReader reader;
command.CommandText = "select * from mycustomers";
connection.Open();
reader = command.ExecuteReader();
using(var sw = new StreamWriter("C:\MyPath\MyFile.txt"))
{
while (reader.Read())
{
var row = (IDataRecord)reader;
sw.WriteLine(row["myColumn"]);
}
}
connection.Close();
If the database is on your local machine you can use 'select .. into outfile'. http://dev.mysql.com/doc/refman/5.1/en/select-into.html. This will write to a folder on the server so it's not v useful if it's a different machine and you can't copy from there.
There are plenty of tutorials out there for accessing MySQL from .NET.
This is one: http://zetcode.com/db/mysqlcsharptutorial/
In any language, there are a few simple steps to read from a database:
1. connect to the database.
2. execute a query
3. iterate through the results of the query
4. close the connection.
What you are doing in your code is connecting to the database and then trying to write the connection information to a file.

Categories