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
Related
Just starting to experiment with F#. I have this code working in C#:
using MySql.Data.MySqlClient;
using System;
using System.IO;
namespace SandboxExecuteReader
{
class Program
{
static void Main(string[] args)
{
MySqlConnection myConnection = new MySqlConnection();
MySqlCommand myCommand = new MySqlCommand();
if (!SQLdbOpen(myConnection, myCommand)) return;
DoWork(myCommand);
myConnection.Close();
return;
}
private static void DoWork(MySqlCommand myCommand)
{
myCommand.CommandText = "SELECT * FROM xxx.mytable";
using (var reader = myCommand.ExecuteReader())
{
while (reader.Read())
{
string Field1 = reader.GetString(reader.GetOrdinal("Field1"));
string Field2 = reader.GetString(reader.GetOrdinal("Field2"));
string Field3 = reader.GetString(reader.GetOrdinal("Field3"));
Console.WriteLine("{0} {1} {2}", Field1, Field2, Field3);
}
}
}
private static bool SQLdbOpen(MySqlConnection myConnection, MySqlCommand myCommand)
{
/*
* Open Connection to SQL DB
*/
string ConnectionString = "server=(someIP); uid=Me; password=MyPass";
try
{
myConnection.ConnectionString = ConnectionString;
myConnection.Open();
myCommand.Connection = myConnection;
}
catch (MySqlException E)
{
Console.WriteLine("Open Error: {0}", E.Message);
Console.WriteLine("Press RETURN to continue or CONTROL-C to abort");
Console.ReadLine();
return false;
}
return true;
}
}
}
Questions:
In C#, I add a reference to MySql.Data.dll. How do I do that in F#?
There seems to be something about #r ... where does that line go? Somewhere in the .fsproj file?
How would this code look in F#?
The first thing you need to decide is whether you are going to run this as a standalone script (.fsx file) or a project (consisting of .fs source files and a .fsproj project file).
If this is going to be a project, it works just like a C# project: you add a reference to MySql.Data.dll in your .fsproj file. If you're using Visual Studio, you can right-click on the project and find MySql.Data in NuGet via the "Manage NuGet Packages..." menu item.
If it's going to be a standalone script, you can add a NuGet reference to MySql by placing this line at the very top: #r "nuget: MySql.Data".
Converting your code from C# is a bit more involved, but your main function might look like this (assuming this is a .fs file):
open MySql.Data.MySqlClient
let sQLdbOpen (myConnection : MySqlConnection) (myCommand : MySqlCommand) =
// ...
true
let doWork (myCommand : MySqlCommand) =
// ...
()
[<EntryPoint>]
let main args =
use myConnection = new MySqlConnection()
use myCommand = new MySqlCommand()
if sQLdbOpen myConnection myCommand then
doWork myCommand
myConnection.Close()
0
(Caveat: I did this translation by eye, so it might not be exactly right.)
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;"/>
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();
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;
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;
}