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
Related
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.
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.
I am trying to make a simple app that will connect to a database and get some info. I have implented the plugin that allows xamarin app to connect remote mariaDB/MySQL to components. I am using the code below.
public void GetAccountCountFromMySQL()
{
try
{
string sql = " SELECT * FROM Kategorier";
MySqlConnection con = new MySqlConnection("Persist Security Info=False; Server=192.210.241.161; Port=3306; Database=xxxxx; Uid=xxxxx; Pwd=xxxxx;");
MySqlCommand cmd = new MySqlCommand(sql, con);
con.Open();
MySqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
Console.WriteLine(reader.GetString("Sko"));
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
I have tried many types of connection strings, also I buileded a simple C# application that connects to the very same database with no problems.
Actual problem was error from MySql "cannot resolve host name" After discussion the decision was not to use this plugin as it is not secured but create a webservice talking to MySql DB and consume it from Android app.
This question already has answers here:
ExecuteReader requires an open and available Connection. The connection's current state is Connecting
(2 answers)
Closed 7 years ago.
My ERP web application written in c#.net throwing this error frequently
I have Globals.cs file under App_Code folder like:
using System;
using System.Data;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Data.SqlClient;
using System.Data.Sql;
public static class Globals
{
public static string mycon = ConfigurationManager.ConnectionStrings["WebConnStr"].ConnectionString;
public static SqlConnection con = new SqlConnection(mycon);
public static SqlCommand cmd = new SqlCommand();
public static SqlDataReader dr;
public static void Initialize(string CmdType, string CmdText)
{
try
{
if (con.State == ConnectionState.Open)
{
con.Close();
}
con.Open();
cmd.Connection = con;
if (CmdType == "StoredProcedure")
{
cmd.CommandType = CommandType.StoredProcedure;
}
else
{
cmd.CommandType = CommandType.Text;
}
cmd.CommandText = CmdText;
cmd.Parameters.Clear();
}
catch (Exception ex)
{
}
}
}
my connection string in web.config looks like:
<connectionStrings>
<add name=WebConnStr connectionString="Data Source=servername;Initial Catalog=dbname;User ID=username; Password=12345" providerName="System.Data.SqlClient"/>
</connectionStrings>
my sample aspx.cs codes like:
Gridview Bind:
DataTable dt = new DataTable();
Globals.Initialize("StoredProcedure", "[sp_getemp]");
Globals.dr = Globals.cmd.ExecuteReader();
dt.Load(Globals.dr);
GridView1.DataSource = dt;
GridView1.DataBind();
Insert Query:
Globals.Initialize("StoredProcedure", "[sp_insertemp]");
Globals.cmd.Parameters.AddWithValue("#EmpID", txtempid.Text);
Globals.cmd.ExecuteNonQuery();
Data Reading:
private string GetEmpName(string empcode)
{
Globals.Initialize("Text", "SELECT EmpName from tbl_emp where EmpID=#EmpID");
Globals.cmd.Parameters.AddWithValue("#EmpID", empcode);
Globals.dr = Globals.cmd.ExecuteReader();
if (Globals.dr.Read() == true)
{
return Globals.dr["EmpName"].ToString();
}
else
{
return "";
}
}
May I know what might have gone wrong in Globals.cs file and how do I fix it?
That is why you should be using the using statement to get rid of this type of error. Something like
using (SqlConnection connection = new SqlConnection(connectionString))
{
//some code
}
You can refer this MSDN and read about connection pooling:
In practice, most applications use only one or a few different
configurations for connections. This means that during application
execution, many identical connections will be repeatedly opened and
closed. To minimize the cost of opening connections, ADO.NET uses an
optimization technique called connection pooling.
Connection pooling reduces the number of times that new connections
must be opened. The pooler maintains ownership of the physical
connection. It manages connections by keeping alive a set of active
connections for each given connection configuration. Whenever a user
calls Open on a connection, the pooler looks for an available
connection in the pool. If a pooled connection is available, it
returns it to the caller instead of opening a new connection. When the
application calls Close on the connection, the pooler returns it to
the pooled set of active connections instead of closing it. Once the
connection is returned to the pool, it is ready to be reused on the
next Open call.
Looks like you need to open a connection before executing code, and example being conn.Open();
I'm developing a Windows CE app in C# and trying to connect to an Oracle database. I'm using CoreLab.Oracle reference. This is my code:
using CoreLab.Oracle;
namespace SmartDeviceProject1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
OracleConnection conn = new OracleConnection();
conn.ConnectionString = "User ID=name;Password=pass;Host=ip;Pooling=true;Min Pool Size=0;Max Pool Size=100;Connection Lifetime=0;Port=1522;Sid=bleh;Unicode=True";
conn.Open();
OracleCommand cmd = new OracleCommand();
cmd.Connection = conn;
cmd.CommandText = "Select * from dc_emp ";
cmd.CommandType = CommandType.Text;
OracleDataReader dr = cmd.ExecuteReader();
dr.Read();
label1.Text = dr.GetString(0);
conn.Dispose();
}
}
}
Every time I run the project conn.Open(); gets error : Network error:: A Socket operation was attempted to an unreachable host. So something is wrong with my connection string but I don't know what.
I might add that when I drag and drop a "oracleConnection" component to my form in design mode and edit the properties, my connection is created.
I have read in some forums I must set the "direct" property to true in my connection string, but when I add it to my connection string it says : Unknown connection string parameter Direct
Can someone please help me?
This is now working! FINALLY FIGURED IT OUT. Had to install Virtual PC 2007 for the VS Emulators. Then configure the Emulator to use the virtual network card.