Database connection troubleshooting - c#

I recently picked up C# programming and am hoping to read in tables from mySQL tables and display them in DataGridView controls. The tables are generated using PHP scripts and I am able to login to my database. In PHP I am using the following connection string:
#mysql_connect('localhost:3307','root','password_string');
In C#, I am using the following connection string:
string MyConString = #"Server=localhost;Database=database_name;User ID=root;Password=password_string";
When I run the program, I get the following message in the console:
"Access denied for user 'root'#'localhost' "
I've tried making countless changes to the connection string by using single quotes, using localhost:3307, etc. I've granted privileges for user root, so I don't think that is the issue. How do I get past this? Is there some problem with the connector I have. Any ideas would be much appreciated.

In PHP you are connecting to the non standard port 3307. You can specify this in the .NET connection string with port=3307:
string MyConString = #"Server=localhost;Database=database_name;User ID=root;Password=password_string;port=3307";

This may be due to PRIVILEGES may be user name do'nt have the required PRIVILEGES
mysql> GRANT ALL PRIVILEGES ON *.* TO 'root'#'localhost'
Other reason may be
This is not possible, as the client always uses a socket to connect to "localhost" (which is the default host). For a sucessful connection either the combination of localhost + socket or 127.0.0.1 + port must be specified.
kimiko:~ # mysql -h127.0.0.1 -P3307 -ptest
kimiko:~ # mysql -S/path/to/mysql.sock -ptest

Related

C# MySql error: MySql.Data.MySqlClient.MySqlException [duplicate]

Trying to connect to MySQL on my web host, using Connector/Net C#/WinForms in Visual Studio 2012 Update 3, but getting the below error message:
Authentication to host '1.1.1.1' for user 'username#mydomain.com' using method 'mysql_native_password' failed with message: Access denied for user 'username#mydomain.com'#'2.2.2.2' (using password: YES)
string connectionString = "SERVER=1.1.1.1;PORT=3306;DATABASE=databaseName;UID=username#mydomain.com;PASSWORD=mypassword;";
MySqlConnection connection = new MySqlConnection(connectionString);
connection.Open();
I am connecting remotely, have whitelisted my IP (and even temporary whitelisted all (%) to test), triple checked the username and password and IP.
I originally tried the username without the domain ( username rather than username#mydomain.com) but it gave me the below error:
Authentication with old password no longer supported, use 4.1 style passwords.
Any assistance would be much appreciated, thanks!
Its problem of 'Remote Database Access Hosts'.
"You can allow external web servers to access your MySQL databases by adding their domain name to the list of hosts that are able to access databases on your web site."
MySql access is not granted to IP address of the system at which application is running.(in your case its '2.2.2.2' ).
Note:- '2.2.2.2' is your public IP address.
Two possible things:
MySQL is case sensitive make sure that the case of Database= in your connection string matches with the actual database name
You may have to grant privileges to the user.
I hope this help you.
Check your application settings file (or wherever you have stored the connection string).
In my case the application was using the old connection string (which was not valid). I was assuming that the change I made in the code of the settings file is reflected to the designer (of the settings file). But it was not!
After creating a new user in MySQL, in MySQL Workbench "Test Connection" will succeed but the C# MySqlConnection.Open() will throw the same exception and message as the question (tested with localhost and 127.0.0.1 and the local ip address).
The reason is that MySqlConnection.Open() will somehow use SELECT privilege, and you need to at least enable the SELECT privilege for the new user. The error message is misleading.
This might be related to the case of specific Membership SQL Server based instructions on ASP.NET 4.5, workaround is to create new membership in web.config, drop mvc 4 AccountControler and use old from MVC3 more here or in the internet:
http://www.nsilverbullet.net/2012/11/06/using-mysql5-as-membership-backend-for-aspnet45-mvc4-application/
In my case updated password was not used. I just generated the password using Password Generator and copy it but forgot to click Change Password.
Also check the user is added to the database and has Privileges.
For me, using the actual IP address instead of the domain name solved the problem
While Whitelisting my Ip on cpanel i had accidentally put a space in there after my ip address.[Should have been handled by them]
I added the ip again and it worked.
In my case, the problem was misleading as well.
Had quite a few windows terminals running "the same" .net app all connecting to a remote MySQL server (installed in a windows server machine). However, only one always popping the specific error when anyone clicked to run the .net application. ODBC test connection passed successfully, and no matter if the error popped, when presing OK the application continued loading successfully finally and then worked fine.But again afterwards , when anyone tried to run in for the first time the message appeared. and I repeat only in this specific terminal! The fix finally came when I noticed, that it was only in this specific terminal with the problem that we had forgotten DHCP enabled! and "although it was given always the same IP" from our IT policies, however it only worked when we disabled DHCP and set this IP, SUBNET and GW, as fixed !
Check with a program like Navicat that the mysql server user has a native password. Everything is correct but if you are getting this error check the version of the link DLL
This error; Mysql.Data.dll and Mysql Server version mismatch error. Download and install an older version
https://downloads.mysql.com/archives/c-net/
Mysql Version < 4.5
Mysql.Data.Dll version= 6.0.3

SQL Server Express Connection String Error in C#

I want to run a small C# program. Its database is on my local host in SQL Server. Now I want to change it to an SQL Server Express one. I have made a database which its name is exactly same with the one in local host, I have made the tables too.
Now I want to change the connection string. What syntax should I use?
I have used this one:
Server = localhost\SQLEXPRESS; Database = MyStore_DB; Trusted_Connection = true
I have used it in MyStore.App.exe.config and MyStore.DataLayer.dll.config files instead of the previous connection string in part ConnectionStrings.
But an error occurs. Could you please help me if I'm mistaken in any step?
error:
the picture of the error occured
Your connection string it's wrong. Once you've declared TrustedConnection=true (you miss the ';' at the end) it means that you will login into the database using Windows Authentication.
Beyonds that, if you wanted to login with an specific user and password, you may try this:
Server=.\\SQLEXPRESS;Database=YourDB;MultipleActiveResultSets=true;User Id=yourUser;Password=yourPassword;
Notice I'm using "." instead of localhost

Windows Service SQL Server error - "Login failed for user"

I have a Windows Service written in C# being run on a Windows Server 2012 R2 machine which connects to a remote SQL Server 2012 instance also on a Windows Server 2012 R2 Server.
The SQL Connection String is defined in the App Config as follows:
<connectionStrings>
<add name="destinationConnectionString" providerName="System.Data.SqlClient"
connectionString="Server=10.42.42.10;Database=mydb;User ID=myuser;Password=mypass" />
</connectionStrings>
When running the service, the output error log shows:
System.Data.SqlClient.SqlException (0x80131904): Login failed for user
'myuser'.
Error Number:18456, State:1, Class:14
So I check the SQL Server Logs to find out more information about the error and find this
Login failed for user myuser Reason: Password did not match for the
login provided"
Source: Logon Message: Error: 18456, Severity: 14, State: 8.
The problem is I know these credentials are correct. I've checked and double checked.
I am able to prove the credentials work by opening SQL Server Management Studio on the source machine, and connecting to the remote SQL Server using the exact same Server, User ID and Password with "SQL Server Authentication" authentication mode.
In fact I have 2 different users that I'm able to connect with using SSMS, but that fail using the Windows service. If I am able to connect to the remote machine using mixed mode auth directly in SSMS. Why not in my Windows service?
I'm at a loss here, could anyone suggest what the issue might be?
Edit: I can even successfully connect to the remote machine using the following command:
sqlcmd -S 10.42.42.10 -U myuser -P mypass -d mydb
The proper syntax for specifying the initial database is:
Server=10.42.42.10;Initial Catalog=mydb;User ID=myuser;Password=mypass
My best guess is that it is ignoring the "Database" in your string and possibly trying to connect to the default database setting for the login (possibly master maybe?) and doesn't have at least public role to it. Although I've found out that "Database" is a valid alternative.
It's possible there is a character in your password that is tripping it up. Semicolons and equal signs will be particularly problematic. Try putting double quotes around your User ID and Password like:
Server=10.42.42.10;Initial Catalog=mydb;User ID="myuser";Password="mypass"
If there's a quotation mark in your password you will have to replace it with two of them for each occurrence.
Once you get your connection string built, then you have to ensure that it will parse properly in XML. Which means escaping control characters and the other special characters such as:
< with <
> with >
& with &
' with &apos;
" with "
If you open up your app config file in a browser it should show you if it looks proper.
I recommend adding the contents of your entire connection string to our output log of your service. That way you can see what it looks like. At the point before you attempt to open the connection, get it with:
string connStr = ConfigurationSettings.AppSettings("myConnectionString");
Then output the connStr value to the log. It will show you what values are being used at least.
You might use some special character in password, that is reserved for XML. If so, you'll need to use escape character as a replacement.
For instance, if your password is PASS<WORD the valid entry in config file would be: PASS<WORD
I have used this site to find the correct pattern
What you have is valid:
Server=myServerAddress;Database=myDataBase;User Id=myUsername;
Password=myPassword;
Are you trying to connect to an instanced sql server? Server=10.42.42.10/SomeInstance
I suggest adding the semicolon, ;, after the password in the connection string. Perhaps it's being parsed weirdly.
I also wonder whether: is a semicolon in your actual password?
Maybe you're attempting a Windows account but there's also a SQL account named the same way. If so, make sure you prefix the Windows account with the domain name. E.g. you might have Windows account of MYDOMAIN\sa with P#ssword, whilst SQL server account is sa and its password is P#ssw0rd.
To make sure what accounts exists, log in the SQL server as an admin and check what accounts are listed under "Security" node of both the server itself and the database of interest.
I had the same problem and here is my solution:
I found out that I was using named instance of an SQL server and changed Server of my connection string from Server=localhost to Server=localhost\SQLEXPRESS and everything worked just fine for me! :)

Access denied for user 'root'#'localhost' (using password: YES) in Visual Studio

Kindly bear with me. I am a Microsoft SQL Server person with loads of Visual Studio experience, but I need to get something done using a MySQL database.
I am trying to create a little tool here that will allow our developers to quickly update database records, and I am using Visual Studio to create a small Windows Form to do this.
In a Microsoft SQL Server connection string, I could write something like this:
Server=myServerAddress;Database=myDataBase;User Id=username;Password=password;
In a MySQL connection string, there appear to be multiple other options, but the first one looks basically the same:
Server=myServerAddress;Database=myDataBase;Uid=username;Pwd=password;
When I attempt to open the MySQL connection from my PC, I get the exception listed in the title (actually, it shows the Uid value and the IP Address of my PC instead of localhost, but I am hoping more people will recognize the error easier this way):
public static void MySQLi_Connect() {
m_err = null;
var str = Properties.Settings.Default.ConnStr;
try {
m_conn = new MySqlConnection(Properties.Settings.Default.ConnStr);
m_conn.Open();
} catch (MySqlException err) {
ErrorLog("MySQLi_Connect", err);
}
}
I did a search, and it seems that the Uid on MySQL needs to be granted access from the specific IP Address that the connection is being made from.
Further, I found this on the mysql.com doc pages:
If you do not know the IP address or host name of the machine from which you are connecting, you should put a row with '%' as the Host column value in the user table. After trying to connect from the client machine, use a SELECT USER() query to see how you really did connect. Then change the '%' in the user table row to the actual host name that shows up in the log. Otherwise, your system is left insecure because it permits connections from any host for the given user name.
A few things:
It looks like I can connect to MySQL by using a % setting in the Uid jp2code, but MySQL says I need to change that back right away to remove system vulnerability.
Microsoft SQL Server did not seem to require this - or, if it did, I simply never was slapped in the face with this vulnerability issue like MySQL is doing.
Now, I ask:
If this is going to be a tool used by different developers on different PCs, is it common practice to turn the blind eye to this horrendous system vulnerability?
Is this not really as big of a concern as MySQL is making it appear?
What is the best way to continue with a Windows Forms application that needs to connect from various locations? Obviously, I do not want to continuously be adding more entries for a particular application every time another developer wants to use the tool or someone tries to run it from a different PC.
You can configure the security of your MySQL server as strong as you like, usually you dont connect users but applications. So if you have your root user without password in production environment is your fault. Usually developers have access to development environment, so this is not a big deal.
Of course try to have as many users as roles you need, for your example I think one user is enough. In production use a secure config file for save a secure password and set you mysqlserver restricted.
I was having the same issue and I found out that the password wasn't correct.
GO to your sql command line and type the code below:
mydb in the line below is the name of the database you are working on.
passwd in the line has to match the password you have in c# code so in your case "password"
grant all privileges on mydb.* to myuser#localhost identified by 'passwd';
Like OP says you can wildcard the hostname portion. I used this on our dev-server (not recommended for production servers):
update mysql.user set host = '%' where host='localhost';
Then I had to restart the server to make MySQL use it (propably I could just have restarted the MySQL service).

how to access my lan based postgresql db from my website

We have lan based .Net application with Postgresql 8.1 , now i have task to provide interface on website to read and write two tables on LAN based database I don't know where to start Please help me to solve this problem.
Lan: Windows NT 2003
.Net
Postgresql 8.1
Website:
PHP 5.3
Mysql
You need to enable remote connections on Postgres. But be wary of security implications.
Haven't read it all, but this should give you an idea on the steps to take on the server. For the connector, you generally just need to point the connect function at the remote IP.
Here is how to do the trick. Copied from here:
<?php
// Connecting, selecting database
$dbconn = pg_connect("host=localhost dbname=publishing user=www password=foo")
or die('Could not connect: ' . pg_last_error());
// Performing SQL query
$query = 'SELECT * FROM authors';
$result = pg_query($query) or die('Query failed: ' . pg_last_error());
// Printing results in HTML
echo "<table>\n";
while ($line = pg_fetch_array($result, null, PGSQL_ASSOC)) {
echo "\t<tr>\n";
foreach ($line as $col_value) {
echo "\t\t<td>$col_value</td>\n";
}
echo "\t</tr>\n";
}
echo "</table>\n";
// Free resultset
pg_free_result($result);
// Closing connection
pg_close($dbconn);
?>
in the above code, replace localhost by the IP-address of your Postgres host.
On Linux, two files need to be modified to allow connections other than from localhost:
postgresql.conf, change the listen_addresses = "*" to accept connections from anywhere. Then add a line to the pg_hba.conf file to allow access to the database from a particular IP or network. If you are not worried about security, entering:
host all all 192.168.1.0/24 trust
will allow anyone on the 192.168.1.0/24 network access to any database. Obviously this should only be used to test you can reach the database. Constrain this to the web servers IP address and use md5 so encrypted password authentication is used.

Categories