VS C# connected to mySQL database - c#

I am very new in C# and now try to find online resource to connect VS C# to mySQL database at server 'localhost', with userid 'root', and password '****', the databasename is 'dlht'.
1.I copied a line of code from youtube and it works:
this.stockTableAdapter.Fill(this.blhsDataSet.stock);
Can anyone explain to me what exactly this is doing? There is no place to put server, password, userid etc... How can it work?
I tried to use the online tutorials to connect to mySQL database
ZetCode C#Tutorial
string cs = #"server=localhost;userid=root;
password=****;database=dlht";
MySqlConnection conn = null;
try
{
conn = new MySqlConnection(cs);
conn.Open();
Console.WriteLine("MySQL version : {0}", conn.ServerVersion);
} catch (MySqlException ex)
{
Console.WriteLine("Error: {0}", ex.ToString());
} finally
{
if (conn != null)
{
conn.Close();
}
}
I run this code at Form1.cs at VS C#. It is always stuck at :
conn = new MySqlConnection(cs);
Why? Thank you so much!

It seems that the proper way to connect to MySql database is this
Server=myServerAddress;Database=myDataBase;Uid=myUsername;Pwd=myPassword;

Related

How to test for database availability in c# script task for an oledb connection

I have to check for database availability using c# scripting for an "oledb" connection in an ssis package.
Since my connection is oledb I'm not able to use AcquireConnection method.
I tried using ConnectionString property of ConnectionManager but I get the connection string even when database is offline.
Any idea how to go about with unmanaged Objects here oledb.
You can find the complete documentation here https://learn.microsoft.com/en-us/dotnet/framework/data/adonet/ado-net-code-examples
what you may need to test the oledb connection is then something like this:
string connectionString =
"Provider=Microsoft.Jet.OLEDB.4.0;Data Source="
+ "c:\\Data\\Northwind.mdb;User Id=admin;Password=;";
OleDbConnection connection = new OleDbConnection(connectionString);
try
{
connection.Open();
connection.Close();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
return true;

failed to connect to database using c#

I want to ask about connecting db with c#.
I have read http://csharp.net-informations.com/data-providers/csharp-sql-server-connection.htm and written my code, but the connection doesn't seem to be working.
This is my code:
string connetionString = null;
SqlConnection connection;
SqlCommand command;
string sql = null;
SqlDataReader dataReader;
connetionString = "Data Source=localhost;Initial Catalog=dbabc;User ID=admin;Password=qwerty";
sql = "UPDATE ppd,brg,cmp SET WHERE";
connection = new SqlConnection(connetionString);
try
{
connection.Open();
command = new SqlCommand(sql, connection);
dataReader = command.ExecuteReader();
while (dataReader.Read())
{
MessageBox.Show(dataReader.GetValue(0) + " - " + dataReader.GetValue(1) + " - " + dataReader.GetValue(2));
}
dataReader.Close();
command.Dispose();
connection.Close();
}
catch (Exception ex)
{
MessageBox.Show("Can not open connection ! ");
}
Did I write something wrong? The error message shown always says "Can not open connection"!
The Exception thrown should be a SqlException. Check the ErrorCode on the SqlException and look it up here...
https://learn.microsoft.com/en-us/azure/sql-database/sql-database-develop-error-messages
Rather than catch(Exception ex) your code should do this...
try
{
connection.Open();
....
connection.Close();
}
catch (SqlException ex)
{
MessageBox.Show($"Can not open connection ! ErrorCode: {ex.ErrorCode} Error: {ex.Message}");
}
catch (Exception ex)
{
MessageBox.Show($"Can not open connection ! Error: {ex.Message}");
}
I think you should check server name
if you install SQL server (Standard) on your computer, server name named is (local) or .
If you are using VS create a data source and test the connection string. Go to data> Add new data source. There is find your database server and create the correct string.
Your code is working. I can verify it. Please check your connection string and SQL query. Especially your SQL query. It seems to be wrong.
Try to execute the query in Microsoft SQL Server Management Studio. If there is an error in your query, you can easily find it there.
SQL Update Syntax
UPDATE table_name
SET column1 = value1, column2 = value2...., columnN = valueN
WHERE [condition];
Recommended Readings
https://www.tutorialspoint.com/sql/sql-update-query.htm
https://www.w3schools.com/sql/sql_update.asp
To verify the connection string,
Open the Server Explorer pane. ("View" menu, "Server Explorer" or
use the key shortcut CTRL+Alt+S).
Right-click on the Data Connections, Select Add connection and then
press continue after selecting Microsft SQL Server as the Data source.
Select Refresh and click down arrow and then select your SQL server.
If you cannot find it, enter the server name manually.
You may also have to enter the SQL server credentials.
Select or enter your database name & then press Test Connection.
If you see a Test connection succeeded message, then your SQL server is working.
If you want, you can also get connection string by pressing Advanced.. button and then copying the connection string
In addition, try to an add exception message to catch block. That way, you can easily find the error.
MessageBox.Show("Can not open connection ! \n" + ex.Message);

How to connect to mysql with C# (simple program)

I am a beginner in C # and I intend to create a simple program to check the connection to the mysql server (in this case I am using xampp, so the connection is local).
The problem is that the connection to the mysql server does not work, so the "Can not open connection!" box pops up. I appreciate all the explanations. thank you :)
using System;
using System.Data;
using System.Data.SqlClient;
using System.Windows.Forms;
using MySql.Data.MySqlClient;
namespace WindowsFormsApp1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void btnSend_Click(object sender, EventArgs e)
{
SqlConnection cnn;
string server = "localhost";
string database = "test";
string uid = "root";
string password = ""; //im using xampp
string connectionString;
connectionString = "SERVER=" + server + ";" + "DATABASE=" +
database + ";" + "UID=" + uid + ";" + "PASSWORD=" + password + ";";
MySqlConnection connection = new MySqlConnection(connectionString);
cnn = new SqlConnection(connectionString);
try
{
cnn.Open();
MessageBox.Show("Connection Open ! ");
cnn.Close();
}
catch (Exception ex)
{
MessageBox.Show("Can not open connection ! ");
}
}
private void button1_Click(object sender, EventArgs e)
{
this.Close();
}
}
}
Thank you for clarifying the specific problem you're having. That's helpful ;)
Thank you, too, for posting the error message.
In the future, please copy/paste the error as TEXT, not an image.
In this case, it would have been nice to run the error text through Google Translate ;)
THE PROBLEM:
Based on the error message, it sounds like your C# program might be trying to use the SQL Server driver to talk to a MySQL database. That won't work :)
SUGGESTION:
Look at any of these links:
MySQL Connector/Net Developer Guide
MySQL C# tutorial
Connect C# to MySQL
At a minimum, you'll also need to get the MySQL driver (e.g. from NuGet):
how to get new mysql connector for c#
I have the same problem after a while i find out i can not use SqlConnection. SqlConnection is for SQL Server i need to install MySql.Data from NuGet:
Install-Package MySql.Data in your Package Manager Console
then i can create MySqlConnection object and connect to your database:
System.Data.IDbConnection cnn = new MySql.Data.MySqlClient.MySqlConnection("my Connection String");
try
{
cnn.Open();
MessageBox.Show("Connection Open ! ");
cnn.Close();
}

Connect to SQL using OleDbConnection failing

I'm connecting to a remote SQL database using the OleDbConnection but it's failing.
var connection = new OleDbConnection
{
ConnectionString = "Provider=SQLOLEDB;server=MyRemoteIPAddress;Initial Catalog=MyDatabase;User ID=sa;Password=MyPassword"
};
try
{
connection.Open();
connection.Close();
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
The error I am getting is : [DBNETLIB][ConnectionOpen (Invalid Instance()).]Invalid connection.
However if I connect using SqlConnection, it connects ok.
var testConnection = new SqlConnection
{
ConnectionString = "server=MyIPAddress;database=MYDatabase;user id=MyUser;pwd=MyPassword"
};
try
{
testConnection.Open();
testConnection.Close();
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
Why can i connect via SqlConnection and not OleDbConnection?
The environment is not clustered but explicitly specifying the port fixed the issue.
This worked :
"Provider=SQLOLEDB;server=MyRemoteIPAddress,1433;Initial Catalog=MyDatabase;User ID=sa;Password=MyPassword"
Try using a server side code which does all the required functions. so that your application does not directly talk with the remote database. Ping me for further assistance.
you should specify the port 1433 when using OLEDB
Provider=SQLOLEDB;server=MyRemoteIPAddress,1433;Initial
Catalog=MyDatabase;User ID=sa;Password=MyPassword;

Connection to MS SQL Server from smart device

I have the trouble with connection to MS SQL Server from Smart Device Project in Visual Studio 2008.
private void button2_Click(object sender, EventArgs e)
{
string connStr = "Data Source=SERVER-5;Initial Catalog=MydB;Integrated Security=SSPI;Connection Timeout=5";
DataTable data;
using (var connection = new SqlConnection(connStr))
{
try
{
var sda = new SqlDataAdapter("select * from pri_date", connection);
var ds = new DataSet();
sda.Fill(ds);
data = ds.Tables[0];
}
catch (SqlException ex)
{
var exc = ex.InnerException;
}
}
}
I'm trying to run this code in Visual Studio and I'm getting the error "Specified SQL server not found: SERVER-5" .
When I tried to launch this code in Windows application everything worked ok.
It's highly likely that it's a name resolution issue. If you use the server's IP address instead of the name, it will likely work. If that does work, then you need to make sure you have the DNS Server properly set for your device's network adapter.

Categories