Cannot connect to MySQL database in C#.NET - c#

So I'm following this tutorial: http://support.microsoft.com/kb/314145/
and I get an unexpected error: A first chance exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll
My class looks like this:
class Database
{
public Database()
{
string connectionString = "Password=pass;User ID=userid;Initial Catalog=soksko;Data Source=(local)";
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
Console.WriteLine("ServerVersion: {0}", connection.ServerVersion);
Console.WriteLine("State: {0}", connection.State);
}
Console.WriteLine("Database: OK");
}
}
I googled, but I couldnt find anything valuable. I am using MySQL database, it is on the same computer and I am using VS 2013. I successfully added my database to Server Explorer with the same connection information that I use above, but I get exception, when I try to open the connection.

See this link for how a MySQL connection string should look:
ASP.NET use SqlConnection Connect Mysql
See this link for an explanation of the oft mis-used Data Source=(local):
http://blogs.msdn.com/b/sql_protocols/archive/2008/09/19/understanding-data-source-local-in-sql-server-connection-strings.aspx
hint you're not using SQL-Server so it won't work for you

SqlConnection is for MS SQL Server. For MySql you need to use a MySqlConnection class provided by the MySQL connector (http://dev.mysql.com/doc/connector-net/en/index.html)
using MySql.Data.MySqlClient;
using(MySqlConnection myConnection = new MySqlConnection(myConnectionString))
{
myConnection.Open();
// execute queries, etc
}

The tutorial you're using is for Sql Server, not MySQL.

Related

SQLite connection string: 'Version' keyword is not supported in C#

I have a c# winform project that supposes to save data to SQLite database, I've already used the dll properly and it runs without error, but I get an exception when trigger the method with buttonClick event
here the exception i got : Keyword not supported :'version'.
this the connection string:
"Data Source = Diary.db;Version = 3;New = False;Compress = True;";
and this the complete method :
private void AddToDbaseSQL3()
{
try{
string query = "insert into Diary(title,date,mood,wheater,content)
values('"+TitleTextbox.Text+"','"
+dateTimePicker.Value.Date.ToString("yyyy-MM-dd HH:mm")+"','"
+MoodCombobox.SelectedItem+"','"
+WheaterCombobox.SelectedItem+"','"
+ContentTextbox.Text+"');";;
SqlConnection connect2 = new SqlConnection(connection2);
SqlCommand cmd = new SqlCommand(query,connect2);
SqlDataReader read;
connect2.Open();
read = cmd.ExecuteReader();
while(read.Read())
{
}
MessageBox.Show("created");
TitleTextbox.Text = "Title";
TitleTextbox.ForeColor = SystemColors.ControlLight;
ContentTextbox.Clear();
connect2.Close();
}catch(Exception e){
MessageBox.Show(e.Message);
}
}
I've looked to this link:
Keyword not supported: 'version'
and it said to change SqlConnection to SQLiteConnection but it ended with an error, can you tell what's is the right connection string ? or there is something wrong from my code/method? please tell me, thank you, I'm sorry because it's my first time using the SQLite
SqlConnection from System.Data.SqlClient is for SQL Server.
You need an dedicated SQLite ADO.NET provider.
You can found the System.Data.SQLite provider from SQLite team here:
https://system.data.sqlite.org
Or you can use any libre or commercial provider.
You can also use the free and open-source SQLite ODBC driver that works fine and allow to use VS Visual Designers to create strongly typed ADO.NET DataSets, in addition to the use of OdbcConnection, OdbcCommand and so on:
http://www.ch-werner.de/sqliteodbc
C# Reading data from existing SQLite database

C# - Can't connect to remote MySQL server

My problem is that I can't connect to my website remote MySQL server. I have read all answers in stackoverflow.com, but I can't find right answer. Here's my C# code:
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
namespace ConsoleApplication3
{
class Program
{
static void Main(string[] args)
{
SqlConnection con;
string connectionString = #"Server=[IP adress];Port=3306;Database=[database];Uid=[user];Pwd=[pass];";
con = new SqlConnection(connectionString);
try
{
con.Open();
Console.WriteLine ("Connection Open ! ");
}
catch (Exception ex)
{
Console.WriteLine("Can not open connection ! ");
Console.WriteLine(ex.Message); //shows what error actually occurs
}
Console.ReadLine();
}
}
}
Error:
A network-related or instance-specific error occurred while establishing a
connection to SQL Server. The server was not found or was not accessible.
Verify that the instance name is correct and that SQL Server is configured
to allow remote connections. (provider: Named Pipes Provider, error: 40
Could not open a connection to SQL Server)
Any ideas?
When connecting to a MySQL-Database I always used the MySQL Connector you can get here: https://dev.mysql.com/downloads/connector/net/6.9.html
You have to import the MySQL namespaces to your project and then you can use the MySQLConnection instead of the SQLConnection that is, as far as I know, only for MSSQL servers.
http://www.codeproject.com/Tips/423233/How-to-Connect-to-MySQL-Using-Csharp
try the following
string connectionString = #"Server=[IP adress]:3306;Database=[database];Uid=[user];Pwd=[pass];";
instead of
string connectionString = #"Server=[IP adress];Port=3306;Database=[database];Uid=[user];Pwd=[pass];";

Connect to SQL Server 2012 Database with C# (Visual Studio 2012)

Evening all,
I'm trying to connect to a SQL Server 2012 database from C#. My connection settings when using SQL Server Management Studio are as below:-
Server Type: Database Engine
Server Name: Paul-PC\SQLEXPRESS
Authentication: Windows Authentication
Username: Greyed out
Password: Greyed out
The name of the database I'm trying to connect to is "testDB".
Here's my code:
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 DatabaseConnection
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void btnConnect_Click(object sender, EventArgs e)
{
SqlConnection myConnection = new SqlConnection("server=localhost;" +
"Trusted_Connection=yes;" +
"database=testDB; " +
"connection timeout=30");
try
{
myConnection.Open();
MessageBox.Show("Well done!");
}
catch(SqlException ex)
{
MessageBox.Show("You failed!" + ex.Message);
}
}
}
}
Unfortunately, my code fails to connect with the following error:-
"You failed!A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections."
Any suggestions? SQL Server is running locally.
In your connection string replace server=localhost with "server = Paul-PC\\SQLEXPRESS;"
I tested all the answers here, but for me, none worked. So I studied a bit the problem, and finally I found the connection string needed. To get this string, you do:
1. in you project name:
a. right click the project name,
b. click Add,
c. select SQL Server Database (obviously you can rename it as you wish).
Now the new desired database will be added to your project.
2. The database is visible in the Server Explorer window.
3. Left click the database name in the Server Explorer window; now check the Solution Explorer window, and you will find the "Connection String", along side with Provider, State, Type, Version.
4. Copy the connection string provided, and put it in the Page_Load method:
string source = #"Data Source=(LocalDB)\v11.0;AttachDbFilename=c:\x\x\documents\visual studio 2013\Projects\WebApplication3\WebApplication3\App_Data\Product.mdf;Integrated Security=True";
SqlConnection conn = new SqlConnection(source);
conn.Open();
//your code here;
conn.Close();
I renamed my database as Product. Also, in the "AttachDbFilename", you must replace "c:\x\x\documents\" with your path to the phisical address of the .mdf file.
It worked for me, but I must mention this method works for VS2012 and VS2013. Don't know about other versions.
Try:
SqlConnection myConnection = new SqlConnection("Database=testDB;Server=Paul-PC\\SQLEXPRESS;Integrated Security=True;connect timeout = 30");
Replacing server=localhost with server=.\SQLEXPRESS might do the job.
Note to under
connetionString =#"server=XXX;Trusted_Connection=yes;database=yourDB;";
Note: XXX = . OR .\SQLEXPRESS OR .\MSSQLSERVER OR (local)\SQLEXPRESS OR (localdb)\v11.0 &...
you can replace 'server' with 'Data Source'
too you can replace 'database' with 'Initial Catalog'
Sample:
connetionString =#"server=.\SQLEXPRESS;Trusted_Connection=yes;Initial Catalog=books;";
use this style
#"server=.\sqlexpress;"

Connecting C# to SQL Server Compact database

Hi I'm trying to connect an SQL server compact database to my program and I want a button that deletes all entries from the database, when I Press said button the program throws an exception and gives the following error message "A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: SQL Network Interfaces, error: 26 - Error Locating Server/Instance Specified)"
Help Please? =]
Sorry, Code is Below =]
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.Data.SqlServerCe;
namespace Booking_system_Final
{
public partial class PendingJobs : Form
{
SqlConnection sc = new SqlConnection("Data Source=C:\\Users\\Administrator\\My Documents\\BMS_Data.sdf");
public PendingJobs()
{
InitializeComponent();
}
private void PendingJobs_Load(object sender, EventArgs e)
{
// TODO: This line of code loads data into the 'bMSDataSet.Bookings' table. You can move, or remove it, as needed.
this.bookingsTableAdapter.Fill(this.bMSDataSet.Bookings);
// TODO: This line of code loads data into the 'bMS_DataDataSet1.Bookings' table. You can move, or remove it, as needed.
}
private void button1_Click(object sender, EventArgs e)
{
sc.Open();
SqlCommand cmd = new SqlCommand("DELETE FROM Bookings");
cmd.Connection = sc;
cmd.ExecuteNonQuery();
sc.Close();
MessageBox.Show("Database Cleared");
}
}
}
Try use SqlCeConnection class rather than SqlConnection:
SqlCeConnection sqlConnection1 = new SqlCeConnection();
sqlConnection1.ConnectionString = "Data Source = C:\\Users\\Administrator\\My Documents\\BMS_Data.sdf;Persist Security Info=False";
If you want to connect to SQL Server Compact, use SqlCeConnection, SqlCeCommand etc. Add a reference to the SQL Server Compact ADO.NET provider, System.Data.SqlServerCe.dll
Have a look at this blog article: SQL SERVER – FIX : ERROR : (provider: Named Pipes Provider, error: 40 – Could not open a connection to SQL Server)
This goes step-by-step through what you might need to do:
In short:
SQL Server should be up and running.
Enable TCP/IP in SQL Server Configuration
Open Port in Windows Firewall
Enable Remote Connection
Enable SQL Server Browser Service
Create exception of sqlbrowser.exe in Firewall
Recreate Alias
About the where and what to do in each step, you will find more in-depth information in the article.
You may also want to have a look at the Connection strings for SQL Server Compact. There you can find other variations of the connection string you could try to play with.
You seems to be using a bad connection string. (Or the file path is wrong). Check out http://www.connectionstrings.com/sql-server-ce for connection string options.

Problems connecting to a local MySQL database using C# and .NET 2.0

Newb questions incoming.
I'm running MySQL locally and I am having a really hard time connecting to it with C#.
Here's the code I'm using, much of the stuff I've tried out is commented out:
using System;
using System.Collections.Generic;
//using System.Data.Common.DbConnection;
using System.Threading;
using System.Data.OleDb;
using System.Data.SqlClient;
using System.Threading;
namespace mvpde
{
class Program
{
class DataReader_SQL
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main(string[] args)
{
//
// TODO: Add code to start application here
//
try
{
OleDbConnection con = new OleDbConnection(#"Provider=sqloledb;Data Source=127.0.0.1:3306;database=database_name;User id=id;Password=password;");
con.Open();
//Thread.Sleep(9999);
//SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder();
//builder.DataSource = "localhost";
//builder.UserID = "hello";
//builder.Password = "password";
//builder.InitialCatalog = "db_123";
//SqlConnection thisConnection = new SqlConnection(builder.ToString());
//thisConnection.Open();
//SqlCommand thisCommand = thisConnection.CreateCommand();
//thisCommand.CommandText = "SELECT CustomerID, CompanyName FROM Customers";
//SqlDataReader thisReader = thisCommand.ExecuteReader();
//while (thisReader.Read())
//{
// Console.WriteLine("\t{0}\t{1}", thisReader["CustomerID"], thisReader["CompanyName"]);
//}
//thisReader.Close();
//thisConnection.Close();
}
catch (SqlException e)
{
Console.WriteLine(e.Message);
Thread.Sleep(9999999);
}
}
}
}
}
I've copied it nearly verbatim and tried to make it work from this site.
I have installed the MySQL on Windows 7 - I have created the user and the database I'm trying to access and I can do all this just fine using MySQL's own MySQL Workbench 5.2 CE software. I seem to have no clue what I'm doing using C# to connect to it.
All I want is to connect to it and send it a simple query like "USE DATABASE somedb" and then "SELECT TABLE sometable".
Errors I'm getting:
At first (when I used WAMP, before installing the MySQL package from mysql website) I would be able to connect once and see a login error; after that, it's as if the connection wasn't closed properly and I'd be unable to get even that far)
Now that I'm trying to connect to a MySQL instance that is created by MySQL's own software (or by running mysqld.exe) all I ever get is timeout problems\server not found\inaccessible.
Questions:
Am I using the wrong class?
What's the deal with "Provider="? where is the list of all the available variables for that part of the string? What does it mean? Why are the names involved so cryptic?
I imagined connecting to a locally-running MySQL server should be a breeze, but I've no idea what I'm doing.
Thank you.
You should use the MySql/Connector for DotNet.
Download it at this address then change your connection string accordingly.
For example "Server=127.0.0.1;Database=database_name;Uid=id;Pwd=password;Port=3306"
For other options, specific for MySQL, look at www.connectionstrings.com
have you had a look at http://www.connectionstrings.com/mysql ?
You can't use a SQL Connection object. You need a MySQL Connection object which is available in this library.http://www.connectionstrings.com/mysql
Download the MySQL Connection Library and use one of their connection strings provided on the site.
using MySql.Data.MySqlClient;
MySqlConnection myConnection = new MySqlConnection;();
myConnection.ConnectionString = myConnectionString;
myConnection.Open();
//execute queries, etc
myConnection.Close();
Then use the connection object to initalise the connection string and connect to MySQL

Categories