Connecting C# Windows Form Application to Sql Server - c#

I'm connecting my windows form application to SQL server but I get this error "SqlException was unhandled" when I start the program.
Here is my code:
void ShowEmployees()
{
using (SqlConnection Connect = new SqlConnection("Data Source=(local);" + "Database='SanMarDryCleaners';" + "Integrated Security=SSPI;"))
{
string strEmployees = "SELECT * FROM employees;";
SqlCommand cmdEmployees = new SqlCommand(strEmployees, Connect);
SqlDataAdapter daEmployees = new SqlDataAdapter();
daEmployees.SelectCommand = cmdEmployees;
DataSet dsEmployees = new DataSet("EmployeesSet");
daEmployees.Fill(dsEmployees);
Connect.Open();
dgvEmployees.DataSource = dsEmployees;
dgvEmployees.DataMember = dsEmployees.Tables[0].TableName;
}
}
Here is the screenshot:

The error suggest that it can't find the SQL Server. And that makes sense because you are using a SqlConnection class which is for Microsoft SQL Server only. You have to use MySQL libary.
Download it from this site:
http://dev.mysql.com/downloads/connector/net/

The error points to a problem while connecting to the server.
A SqlConnection is for SQL-Servers. Use a library specific to MySQL and a MySqlConnection.
See:
Connector/Net Installation
MySQL Connector/Net connection strings

Related

C# Connection mysql with self signed

Is self signed certificate disrupting connection to mysql?
I already give action crud in data and grant access to administration.
but the connection still got error.
Unable to connect to any of the specified MySQL hosts
my team connection like this:
Catalog=devbaf;User Id=userclient;password=client123
connection code:
try
{
string constring = "SERVER=123.45.678.9;DATABASE=devbaf;User Id=backendsystem;PASSWORD=1q2w3e4r5t;";
using (MySqlConnection con = new MySqlConnection(constring))
{
using (MySqlCommand cmd = new MySqlCommand("SELECT * FROM users"))
{
using (MySqlDataAdapter sda = new MySqlDataAdapter())
{
cmd.Connection = con;
sda.SelectCommand = cmd;
using (DataTable dt = new DataTable())
{
sda.Fill(dt);
gvtest.DataSource = dt;
gvtest.DataBind();
}
}
}
}
}
catch (Exception e)
{
Response.Write(e.Message.ToString());
}
explanation problem:
I make a database in local server, so my friend can access to it to insert data. but when he make a connection script it wont connect to my database but can connect to server. He already tries to move some file to the server and it works,but the connection to database wont connect. i don't have an experience for this coz im php programmer not c# programmer. hope my explanation is clear.
I have found your error message like trying to connect the host but in your connection string is missing the MySQL server name or host address. I hope if you add the MySQL hostname or server address to your connection. it will fix your issue.
you can try this
string connectionString ="SERVER=servername; DATABASE=databasename; User Id=userid; PASSWORD=password;";

Open database into application c#

I have added a SQL Server .mdf database file to my C# application, but when I try to connect with this code, the program causes a connection error.
CODE:
DataSet data;
string con = "Data Source=dbinterno.mdf;";
string queryString = "Select * FROM Dati";
try
{
using (SqlConnection connection = new SqlConnection(con))
{
connection.Open();
SqlDataAdapter adapter = new SqlDataAdapter();
SqlCommand command = new SqlCommand(queryString, connection);
command.ExecuteNonQuery();
data = new DataSet();
adapter.Fill(data);
MessageBox.Show(data.ToString());
connection.Close();
}
}
catch
{
MessageBox.Show("\n Problemi di connessione al database");
}
The error is:
ERROR IMAGE
Here are a couple observations:
Your connection string will need to be modified. Try using
string con = "Server=myServerAddress;Database=myDataBase;Trusted_Connection=True;";
using Windows Authentication or this:
string con = "Server=myServerAddress;Database=myDataBase;User Id=myUsername;
Password=myPassword;"; using standard security, Source: connectionstrings.com. This should be managed some other way than in code as well. Desktop applications can be de-compiled, and if the password changes, you would need a rebuild. In a ASP.NET application, Microsoft advises to use a web.config file or in the windows registry using a custom subkey.
You will want to use ExecuteReader() for a SELECT statement as ExecuteNonQuery() will not return a result set. See this answer that describes the differences in the types of SQL Server methods
you don't need connection.Close();, the using statement will handle that.

connect to MySQL webserver with C#

I try to connect to a MySQL database on a server a friend of mine has created, but it still says it cannot connect to the server!
Here is my code:
String connectionString = "Persist Security Info=False;database=qwertyui;server=www.qwertyuiop.com;Uid=asdfghj;Pwd=qazwsxedc;Connect Timeout=30";
using (SqlConnection connection = new SqlConnection(connectionString))
{
SqlCommand cmd = new SqlCommand("INSERT INTO etc.... ");
cmd.CommandType = CommandType.Text;
cmd.Connection = connection;
cmd.Parameters.AddWithValue( etc.... );
connection.Open();
int r = cmd.ExecuteNonQuery();
}
It failes on the connection.Open() instruction throwing an exception -> cannot connect to the server.
Any ideas please?
SqlConnection is a SQL Server client.
You need to download a MySql client from NuGet.
First download the MySQL Connector.
Make sure you add a reference to the DLL (+ set copy local to true !)
Add using MySql.Data.MySqlClient; on top of your class.
As for the Connection String, do not add http or www in front of server. As it will try to connect to apache (port 80) instead to MySQL. The default port of MySQL is 3306.
string connectionString = "Persist Security Info=False;database=qwertyui;server=qwertyuiop.com;Uid=asdfghj;Pwd=qazwsxedc;port=3306";
using (MySqlConnection connection = new MySqlConnection(connectionString))
{
string query = "INSERT INTO table VALUES (#parameter)";
connection.Open();
using (MySqlCommand cmd = new MySqlCommand(query, connection))
{
cmd.Parameters.AddWithValue("#parameter", parameter);
cmd.ExecuteNonQuery();
}
}
If this is not working. Make sure MySQL allows remote access, if this is not the case, you can keep trying forever without any result.
First thing that comes to mind is that you will have to use a MysqlConnection and command.
http://dev.mysql.com/doc/refman/5.0/es/connector-net-examples-mysqlconnection.html
Is it a local database?
And if with all of above does not work try to get grant to all privileges(GRANT Syntax)!
Basically it will go something like:
GRANT ALL PRIVILEGES ON DBname.* to 'username'#'IPadress' IDENTIFIED BY 'password';

ConnectionString for SQL Server

I have xampp installed in my computer. I am trying to access data with ADO.Net. The connection string I am using is given below:
string connectionString = "Server = localhost; Database = magento; User Id = magento; Password = abcd;";
SqlConnection con = new SqlConnection(connectionString);
string cmdString = "SELECT date_added,title,description,url FROM adminnotification_inbox";
SqlDataAdapter da = new SqlDataAdapter(cmdString, con);
ds = new DataSet();
da.Fill(ds,"prog");
dt = ds.Tables["prog"];
currRec = -1;
totalRec = dt.Rows.Count;
button3.Enabled = true;
I am able to log in with the above user id and password in phpmyadmin, but cannot access the database with the above connection string. please help. Thanks in advance.
MySQL has its own ADO.NET connector: http://dev.mysql.com/downloads/connector/net/6.6.html#downloads
If you use that, you can create a MySqlConnection: http://dev.mysql.com/doc/refman/5.5/en/connector-net-tutorials-intro.html
The basic SqlConnection is used for Microsoft's own SQL Server products.
9-22-14 - Hope others see this if you don't:
You need a driver in your connect string I believe. "MySQL ODBC 3.51 Driver" is the Window's driver name.
string connectionString ="Driver={MySQL ODBC 3.51 Driver}; SERVER= .... ok put the rest of your connect string here.
Note: this is the string to connect to a MySQL db using MS Access VBA:
Dan

C# How to Read from MySQL database Wampserver

I am trying to read a table from a Wampserver using this, but I get an 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: Named Pipes Provider, error: 40 - Could not open a connection to SQL Server)"
When I ping localhost all the pings are received. Is this code correct?
private void button5_Click(object sender, EventArgs e)
{
SqlConnection myConnection = new SqlConnection("user id=root;" +
"password=pass;server=localhost;" +
"database=database; " +
"connection timeout=10");
string query = "select * from table";
SqlCommand cmd = new SqlCommand(query, myConnection);
myConnection.Open(); // the error
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(tabelsql);
myConnection.Close();
da.Dispose();
}
If you're using a WampServer than that means you're using MySQL, right?
MySQL and SQL Server are not the same. SQLConnection, SQLCommand and SQLDataAdapter are used to connect to SQL Server (the RDBMS from Microsoft), not MySQL.
To access a MySQL database from .NET you can use the MySQL Connector.
SqlCommand and SqlDataAdapter are part of the MS SQL ADO.NET native client and can only be used for MS Sql Server. WAMP appears to include MySql. For that, you'll likely want to use the MySql ADO.NET driver found here. And this article provides some sample code for reading MySql data utilizing a DataReader.
To Read a single table from MySql database which is in wamp server.
If wamp-server is in localhost then,
Add reference ..
using MySql.Data.MySqlClient;
And after this..
write below public partial class this connection query..
MySqlConnection cn = new
MySqlConnection
("server=localhost;database=database;userid=root;password=;charsetutf8;");
write this GetData() in your form load event or below InitializeComponent...
private void GetData()
{
cn.Open();
MySqlDataAdapter adp = new MySqlDataAdapter("SELECT * from
tablename", cn);
DataTable dt = new DataTable();
adp.Fill(dt);
dataGridViewName.DataSource = dt;
adp.Dispose();
cn.Close();
}

Categories

Resources