Internal connection fatal error in opening connection - mysql

In Asp.net mvc, I tried to open a sql connection, but it always gives me invalid connection fatal error.
Here is my following code:
In Web.config:
<connectionStrings>
<add name="test" connectionString="Data Source=test,3306;Initial catalog=test;User Id=xxxxx;password=xxxx;Trusted_Connection=False;Encrypt=True;" providerName="System.Data.SqlClient" />
In Controller class:
var sql = "select * from users where email = \"" + model.Email + "\" and password = \"" + model.Password +\"";
System.Diagnostics.Debug.WriteLine("return url = "+sql);
string connectionString = ConfigurationManager.ConnectionStrings["test"].ConnectionString;
using (var conn = new SqlConnection(connectionString))
{
try
{
conn.Open();
SqlCommand cmd = new SqlCommand(sql, conn);
SqlDataReader dr = cmd.ExecuteReader();
dr.Read();
System.Diagnostics.Debug.WriteLine("output = " + dr.HasRows);
conn.Close();
}
catch(Exception e)
{
System.Diagnostics.Debug.WriteLine("exception " + e.ToString());
}
}
It gives me following exception on conn.open();
System.InvalidOperationException: Internal connection fatal error. Error state: 18
Can anyone suggest what is wrong in my code.

public MySqlConnection GetMySqlConnection(string dataBase, string server,uint port,string userID,string pass)
{
MySqlConnectionStringBuilder myBuilder = new MySqlConnectionStringBuilder();
myBuilder.Database = dataBase;
myBuilder.Server = server;
myBuilder.Port = port;
myBuilder.UserID = userID;
myBuilder.Password = pass;
MySqlConnection myconn = new MySqlConnection(myBuilder.ConnectionString);
myconn.Open();
return myconn;
}
Description:
You should use MySql instead of MS SQL.
Install MySql connector net and MySql for Visual Studio ("just google them")
After install:
you must to add MySql.Data in References
in your class: using MySql.Data.MySqlClient;

Related

System.Data.SqlClient.SqlException: 'Login failed for user 'root'

Am trying to connect MySQL Server with ASP.NET web application and am using below connection string and gettign error System.Data.SqlClient.SqlException: 'Login failed for user 'root'.'
Please find my connection string from web.config file.
<connectionStrings>
<add name="EmployeeAppDB" connectionString="server=localhost;database=employeedb;user id=root;password=root;"/>
</connectionStrings>
Please find my controller class below.
namespace WebAPI.Controllers
{
public class DepartmentController : ApiController
{
public HttpResponseMessage Get()
{
DataTable table = new DataTable();
string query = #"
select employeedb.department.DepartmentID, employeedb.department.DepartmentName from employeedb.department";
using (var con = new SqlConnection(ConfigurationManager.ConnectionStrings["EmployeeAppDB"].ConnectionString))
using (var cmd = new SqlCommand(query, con))
using (var da = new SqlDataAdapter(cmd))
{
cmd.CommandType = CommandType.Text;
da.Fill(table); // am getting error in the line `System.Data.SqlClient.SqlException: 'Login failed for user 'root'.'`
}
return Request.CreateResponse(HttpStatusCode.OK, table);
}
}
}
You are using SqlConnection to connect database while you should use MySqlConnection and MySqlCommand to connect and operate with MySQL Server.
Make sure database name and credentials are correct and connection string looks good.
Moreover you can try below connection string:
<add name="EmployeeAppDB" connectionString="Server=localhost; Database=employeedb; Uid=root; Pwd=root;Convert Zero Datetime=True;Connection Timeout=60;"/>

Unable to connect to MySQL database through Visual studio 2012

We encountered an error while trying to connect. Here is my code :
public void BindData()
{
MySqlConnection con = new MySqlConnection("server=localhost;user id=root;database=abc");
con.Open();
MySqlCommand cmd = new MySqlCommand("Select * from register", con);
MySqlDataAdapter adp = new MySqlDataAdapter(cmd);
DataSet ds = new DataSet();
adp.Fill(ds);
GridView1.DataSource = ds;
GridView1.DataBind();
cmd.Dispose();
con.Close();
}
But it gives following error :
You should check if the reference Renci.SshNet is existing in your Projects's references. If none, find the .dll file then add it respectively.
Regards,
Hack Dawg

Azure Functions v2 Connectionstring from application settings

I have made a simple Azure Functions v2 Web Service that connects to an Azure SQL database, runs a stored procedure with 3 parameters and returns the result as JSON output. It works as it is now (with the connectionstring in the run.csx file).
But how do I get it to get the connectionstring from Applications Settings?
I have tried various guides both here and other places. But all I can find is a long list of references and a whole bunch of code I need to add. I have followed the guides to the letter (also set the values in App Settings), but it just wont work. I'm rather new to C#, so it might be I just don't understand what I'm supposed to do.
Anyways this is my code and the suggested fix, as far as I'm able to tell:
#r "Newtonsoft.Json"
#r "System.Data"
using System.Net;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Primitives;
using Newtonsoft.Json;
using System.Data;
using System.Data.SqlClient;
public static async Task<ActionResult> Run(HttpRequest req, ILogger log)
{
log.LogInformation("C# HTTP trigger function processed a request.");
string login = req.Query["login"];
string pwd = req.Query["password"];
string TransID = req.Query["TransID"];
string requestBody = await new StreamReader(req.Body).ReadToEndAsync();
dynamic data = JsonConvert.DeserializeObject(requestBody);
login = login ?? data?.login;
pwd = pwd ?? data?.password;
TransID = TransID ?? data?.TransID;
var cnnString = "Server=MyServer;Database=WebServices;User Id=MyUser;Password=MyPassword;Encrypt=True;";
try
{
DataTable table = new DataTable();
SqlConnection connection = new SqlConnection(cnnString);
SqlCommand cmd = new SqlCommand("sp_GetRegRW", connection);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(new SqlParameter("#Login", login));
cmd.Parameters.Add(new SqlParameter("#Password", pwd));
cmd.Parameters.Add(new SqlParameter("#TransID", TransID));
await connection.OpenAsync();
using (SqlDataAdapter adapter = new SqlDataAdapter(cmd))
{
adapter.Fill(table);
}
return (ActionResult)new OkObjectResult(JsonConvert.SerializeObject(table));
}
catch (SqlException sqlex)
{
return (ActionResult)new OkObjectResult($"The following SqlException happened: {sqlex.Message}");
}
catch (Exception ex)
{
return (ActionResult)new OkObjectResult($"The following Exception happened: {ex.Message}");
}
}
suggested solution:
#r "Newtonsoft.Json"
#r "System.Data"
#r "Microsoft.Extensions.Configuration"
using System.Net;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Primitives;
using Newtonsoft.Json;
using System.Data;
using System.Data.SqlClient;
using Microsoft.Extensions.Configuration;
public static async Task<ActionResult> Run(HttpRequest req, ILogger log, ExecutionContext context)
{
var config = new ConfigurationBuilder()
.SetBasePath(context.FunctionAppDirectory)
.AddJsonFile("local.settings.json", optional: true, reloadOnChange: true)
.AddEnvironmentVariables()
.Build();
var cnnString =config.GetConnectionString("connWS");
var setting1 = config["Setting1"];
log.LogInformation(cnnString);
log.LogInformation(setting1);
log.LogInformation("C# HTTP trigger function processed a request.");
string login = req.Query["login"];
string pwd = req.Query["password"];
string TransID = req.Query["TransID"];
string requestBody = await new StreamReader(req.Body).ReadToEndAsync();
dynamic data = JsonConvert.DeserializeObject(requestBody);
login = login ?? data?.login;
pwd = pwd ?? data?.password;
TransID = TransID ?? data?.TransID;
try
{
DataTable table = new DataTable();
SqlConnection connection = new SqlConnection(cnnString);
SqlCommand cmd = new SqlCommand("sp_GetRegRW", connection);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(new SqlParameter("#Login", login));
cmd.Parameters.Add(new SqlParameter("#Password", pwd));
cmd.Parameters.Add(new SqlParameter("#TransID", TransID));
await connection.OpenAsync();
using (SqlDataAdapter adapter = new SqlDataAdapter(cmd))
{
adapter.Fill(table);
}
return (ActionResult)new OkObjectResult(JsonConvert.SerializeObject(table));
}
catch (SqlException sqlex)
{
return (ActionResult)new OkObjectResult($"The following SqlException happened: {sqlex.Message}");
}
catch (Exception ex)
{
return (ActionResult)new OkObjectResult($"The following Exception happened: {ex.Message}");
}
}
In function v2, you should use Environment.GetEnvironmentVariable("string_name",EnvironmentVariableTarget.Process) to get values from Application settings and connection strings.
Note: When use the above method, the first parameter depends on the Type. It means that when the type of the connection string is SQLAZURE, then the first parameter should be SQLAZURE + CONNSTR + _stringName.
The screenshot is as below:
The code sample:
//for connection string
string connStr = Environment.GetEnvironmentVariable("SQLAZURECONNSTR_sqldb_connection",EnvironmentVariableTarget.Process);
log.LogInformation("the connection string is: " + connStr);
And the result snapshot:
I get the following error: The ConnectionString property has not been initialized.
You should probably create an instance of SqlConnection, with your connection string and open this connection before try to make any command.
SqlConnection con = new SqlConnection("connStr");
await con.OpenAsync();

Xamarin SqlConnection throwing error Input string was not in correct format

Im trying to connect my mobile to PC database using this code:
string cString = #"Persist Security Info=False;Integrated Security=false;Initial Catalog=myDB;server=192.168.1.11,1433\SqlExpress";
SqlConnection connection = new SqlConnection(cString);
connection.Open();
using (SqlCommand cmd = new SqlCommand("SELECT name1 FROM Product", connection))
{
using (SqlDataReader rdr = cmd.ExecuteReader())
{
while (rdr.Read())
{
t.Text += rdr.GetString(rdr.GetOrdinal("name1")) + System.Environment.NewLine;
}
}
}
Unfortunately I'm getting error: "Input string was not in the correcr format", source: mscorlib.
I know that there's error in connectionString (throwin exception after connection.Open())
Any ideas? Thanks in advance!
your current Culture is not in correct format
protected override void OnResume()
{
base.OnResume();
//Here you would read it from where ever.
var userSelectedCulture = new CultureInfo("en-US");
Thread.CurrentThread.CurrentCulture = userSelectedCulture;
}

Mysql .NET Connection String Error

My database is on online which is cheapitservice.com. The Mysql connector produces error like this:
Unable to connect to any of the specified MySQL hosts
And my code is:
dbConn.ConnectionString = "Server=......hostedresource.com;Database=sampledb;user=user;password=test;"; dbConn.Open();
Is there something wrong with my code? Please help me.
mySQLconnector is version 6.6.5
you can use this link to make works your code... ConnectionsString with this you can realize whats wrong...
Example:
static void Main(string[] args)
{
var ConnectionString = #"server=localhost; user=root; password=a54321; database=Prueba";
using (MySqlConnection con = new MySqlConnection(ConnectionString))
{
con.Open();
using (MySqlCommand Command = new MySqlCommand("SELECT IdEmpleado, Nombres, Apellidos, Correo, Telefono FROM Empleados", con))
using (MySqlDataReader Reader = Command.ExecuteReader())
{
while (Reader.Read())
{
Console.WriteLine("{0} - {1} - {2} - {3} - {4}",
Reader.GetInt32(0), Reader.GetString(1), Reader.GetString(2), Reader.GetString(3), Reader.GetString(4));
}
}
}
Console.ReadKey();
}
Regards